diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..d13affe36 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Ensure all Java files use LF. +*.java eol=lf diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index bb80b8491..46f209338 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4,4 +4,4 @@ # See: https://help.github.com/articles/about-codeowners/ # These owners will be the default owners for everything in the repo. -* @hevayo @indikasampath2000 @aneeshafedo @lnash94 +* @hevayo @nipunaranasinghe @lnash94 diff --git a/.github/workflows/build-timestamped-master.yml b/.github/workflows/build-timestamped-master.yml index 030ab03b6..f2343c9fd 100644 --- a/.github/workflows/build-timestamped-master.yml +++ b/.github/workflows/build-timestamped-master.yml @@ -11,11 +11,11 @@ jobs: if: github.repository_owner == 'ballerina-platform' steps: - uses: actions/checkout@v2 - - name: Set up JDK 11.0.7 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: 11 + java-version: 17.0.7 - name: Change to Timestamped Version run: | startTime=$(TZ="Asia/Kolkata" date +'%Y%m%d-%H%M00') diff --git a/.github/workflows/central-publish.yml b/.github/workflows/central-publish.yml index 9bfc07817..83ff232e8 100644 --- a/.github/workflows/central-publish.yml +++ b/.github/workflows/central-publish.yml @@ -9,11 +9,11 @@ jobs: if: github.repository_owner == 'ballerina-platform' steps: - uses: actions/checkout@v2 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: 11 + java-version: 17.0.7 - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Publish artifact diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f459fe106..6a42f1b80 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -8,11 +8,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Set up JDK 11.0.7 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: 11 + java-version: 17.0.7 - name: Set version env variable run: echo "VERSION=$((grep -w "version" | cut -d= -f2) < gradle.properties | rev | cut --complement -d- -f1 | rev)" >> $GITHUB_ENV - name: Pre release depenency version update diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index b4570cc6d..6e44ef5c1 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -15,11 +15,11 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up JDK 11.0.7 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: 11 + java-version: 17.0.7 - name: Build with Gradle env: packageUser: ${{ github.actor }} @@ -36,11 +36,11 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up JDK 11.0.7 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: 11 + java-version: 17.0.7 - name: Build with Gradle env: packageUser: ${{ github.actor }} diff --git a/README.md b/README.md index 8214b3c85..a8fdc465b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ The `openapi` command in Ballerina is used for OpenAPI to Ballerina and Ballerin The OpenAPI compiler plugin will allow you to validate a service implementation against an OpenAPI contract during compile time. This plugin ensures that the implementation of a service does not deviate from its OpenAPI contract. -For more information on the supported operations, go to [Using the OpenAPI Tools](https://ballerina.io/swan-lake/learn/using-the-openapi-tools/) +For more information on the supported operations, go to [Using the OpenAPI Tools](https://ballerina.io/learn/openapi-tool/) ## Building from the Source ### Setting Up the Prerequisites @@ -68,7 +68,7 @@ All contributors are encouraged to read the [Ballerina Code of Conduct](https:// ## Useful Links * Discuss about code changes of the Ballerina project in [ballerina-dev@googlegroups.com](mailto:ballerina-dev@googlegroups.com). -* Chat live with us via our [Slack channel](https://ballerina.io/community/slack/). +* 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. * View the [Ballerina performance test results](https://github.com/ballerina-platform/ballerina-lang/blob/master/performance/benchmarks/summary.md). diff --git a/build.gradle b/build.gradle index c72694802..c61f28fc0 100644 --- a/build.gradle +++ b/build.gradle @@ -17,17 +17,19 @@ plugins { id "base" id 'maven-publish' - id "com.github.spotbugs" version "4.0.5" - id "com.github.johnrengelman.shadow" version "5.2.0" - id "de.undercouch.download" version "4.0.4" + 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 "org.sonarqube" version "4.0.0.2929" } apply plugin: 'java' apply plugin: "com.github.spotbugs" apply plugin: 'jacoco' apply plugin: "org.javamodularity.moduleplugin" +apply from: "$rootDir/gradle/javaProject.gradle" ext.ballerinaLangVersion = project.ballerinaLangVersion ext.testngVersion = project.testngVersion @@ -54,8 +56,9 @@ ext.stdlibGraphqlVersion = project.stdlibGraphqlVersion ext.stdlibGrpcVersion = project.stdlibGrpcVersion ext.stdlibWebsubVersion = project.stdlibWebsubVersion ext.stdlibConstraintVersion = project.stdlibConstraintVersion +ext.stdlibWebsocketVersion = project.stdlibWebsocketVersion ext.jacocoVersion = project.jacocoVersion -ext.puppycrawlCheckstyleVersion = "8.18" +ext.puppycrawlCheckstyleVersion = project.puppycrawlCheckstyleVersion allprojects { group = 'io.ballerina' @@ -92,17 +95,6 @@ allprojects { url "https://plugins.gradle.org/m2/" } } - // Add checkstyles - checkstyle { - toolVersion '8.16' - configFile = file("$rootProject.projectDir/config/checkstyle/checkstyle.xml") - } - - def excludePattern = '**/module-info.java' - tasks.withType(Checkstyle) { - configFile file("${rootProject.projectDir}/config/checkstyle/checkstyle.xml") - exclude excludePattern - } ext { snapshotVersion= '-SNAPSHOT' @@ -139,6 +131,7 @@ subprojects { ballerinaStdLibs "io.ballerina.stdlib:graphql-ballerina:${stdlibGraphqlVersion}" ballerinaStdLibs "io.ballerina.stdlib:grpc-ballerina:${stdlibGrpcVersion}" ballerinaStdLibs "io.ballerina.stdlib:websub-ballerina:${stdlibWebsubVersion}" + ballerinaStdLibs "io.ballerina.stdlib:websocket-ballerina:${stdlibWebsocketVersion}" ballerinaStdLibs "io.ballerina.stdlib:constraint-ballerina:${stdlibConstraintVersion}" } @@ -168,6 +161,9 @@ tasks.withType(JavaCompile) { } task codeCoverageReport(type: JacocoReport) { dependsOn = subprojects.test + dependsOn(":test") + dependsOn(":openapi-extension-tests:jacocoTestReport") + dependsOn(":openapi-integration-tests:jacocoTestReport") executionData fileTree(project.rootDir.absolutePath).include("**/build/coverage-reports/*.exec") @@ -175,9 +171,9 @@ task codeCoverageReport(type: JacocoReport) { sourceSets it.sourceSets.main } reports { - xml.enabled = true - html.enabled = true - csv.enabled = true + xml.required = true + html.required = true + csv.required = true xml.destination = new File("${buildDir}/reports/jacoco/report.xml") html.destination = new File("${buildDir}/reports/jacoco/report.html") csv.destination = new File("${buildDir}/reports/jacoco/report.csv") @@ -188,3 +184,11 @@ task codeCoverageReport(type: JacocoReport) { } } +sonar { + properties { + property "sonar.projectKey", "ballerina-platform_openapi-tools" + property "sonar.organization", "ballerina-platform" + property "sonar.host.url", "https://sonarcloud.io" + } +} + diff --git a/config/checkstyle/build.gradle b/config/checkstyle/build.gradle index 8905fbae8..e74f12d16 100644 --- a/config/checkstyle/build.gradle +++ b/config/checkstyle/build.gradle @@ -19,10 +19,10 @@ plugins { id "de.undercouch.download" } -task downloadMultipleFiles(type: Download) { +task downloadCheckstyleRuleFiles(type: Download) { src([ - 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/checkstyle.xml', - 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/suppressions.xml' + 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.4/checkstyle/jdk-17/checkstyle.xml', + 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.4/checkstyle/jdk-17/suppressions.xml' ]) overwrite false onlyIfNewer true @@ -37,10 +37,10 @@ clean { enabled = false } -artifacts.add('default', file("${rootDir}/config/checkstyle/checkstyle.xml")) { - builtBy('downloadMultipleFiles') +artifacts.add('default', file("$project.buildDir/checkstyle.xml")) { + builtBy('downloadCheckstyleRuleFiles') } -artifacts.add('default', file("${rootDir}/config/checkstyle/suppressions.xml")) { - builtBy('downloadMultipleFiles') +artifacts.add('default', file("$project.buildDir/suppressions.xml")) { + builtBy('downloadCheckstyleRuleFiles') } diff --git a/gradle.properties b/gradle.properties index f87bd5d36..45e4fbf10 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,40 +1,55 @@ org.gradle.caching=true group=io.ballerina -version=1.2.0-SNAPSHOT +version=1.8.0-SNAPSHOT #dependency -ballerinaLangVersion=2201.2.0-20220714-175300-1f0ead80 -testngVersion=7.4.0 +ballerinaLangVersion=2201.8.0-20230816-121900-c1174ddd +testngVersion=7.6.1 slf4jVersion=1.7.30 -org.gradle.jvmargs=-Xmx4096M +org.gradle.jvmargs=-Xmx4096M -Dfile.encoding=UTF-8 commonsLang3Version=3.9 commonsIoVersion=2.6 netLingalaZip4jVersion=2.8.0 -jacocoVersion=0.8.6 - -#stdlib -stdlibIoVersion=1.2.2 -stdlibRegexVersion=1.3.0 -stdlibFileVersion=1.3.0 -stdlibOsVersion=1.3.0 -stdlibLogVersion=2.3.0 -stdlibMimeVersion=2.3.0 -stdlibCryptoVersion=2.2.2 -stdlibAuthVersion=2.3.0 -stdlibHttpVersion=2.3.1-20220715-183500-7edae09 -stdlibTimeVersion=2.2.2 -stdlibTaskVersion=2.2.2 -stdlibCacheVersion=3.2.2 -stdlibJwtVersion=2.3.0 -stdlibOAuth2Version=2.3.0 -stdlibUuidVersion=1.3.0 -stdlibUrlVersion=2.2.2 -stdlibXmldataVersion=2.2.2 -stdlibGraphqlVersion=1.3.1 -stdlibGrpcVersion=1.3.0 -stdlibWebsubVersion=2.3.0 -stdlibConstraintVersion=1.0.0-20220711-153400-5cab109 +jacocoVersion=0.8.10 +swaggerParserVersion=2.1.16 +puppycrawlCheckstyleVersion = 10.12.1 + +# Stdlib Level 01 +stdlibIoVersion=1.5.0 +stdlibRegexVersion=1.4.3 +stdlibTimeVersion=2.3.0 +stdlibUrlVersion=2.3.0 +stdlibXmldataVersion=2.6.0 + +# Stdlib Level 02 +stdlibConstraintVersion=1.3.0 +stdlibCryptoVersion=2.4.0 +stdlibLogVersion=2.8.1-20230718-085900-36c385c +stdlibOsVersion=1.7.0 +stdlibTaskVersion=2.4.0 + +# Stdlib Level 03 +stdlibCacheVersion=3.6.0 +stdlibFileVersion=1.8.0 +stdlibMimeVersion=2.8.0 +stdlibUuidVersion=1.6.0 + +# Stdlib Level 04 +stdlibAuthVersion=2.9.0 +stdlibJwtVersion=2.9.0 +stdlibOAuth2Version=2.9.0 + +# Stdlib Level 05 +stdlibHttpVersion=2.10.0-20230809-150400-0c9cad9 + +# Stdlib Level 06 +stdlibGrpcVersion=1.9.1-20230809-211700-feffbef +stdlibWebsocketVersion=2.9.1-20230809-174700-6942521 +stdlibWebsubVersion=2.9.1-20230809-211400-c6c75d2 + +# Stdlib Level 07 +stdlibGraphqlVersion=1.10.0-20230809-214800-d775b0d # Ballerinax Observer -observeVersion=1.0.4 -observeInternalVersion=1.0.3 +observeVersion=1.1.0 +observeInternalVersion=1.1.0 diff --git a/gradle/javaProject.gradle b/gradle/javaProject.gradle index 6d9ec1c9b..c803f3bd1 100644 --- a/gradle/javaProject.gradle +++ b/gradle/javaProject.gradle @@ -15,7 +15,7 @@ * */ -apply plugin: "java" +apply plugin: "java-library" apply plugin: "com.github.spotbugs" apply plugin: "checkstyle" apply plugin: "jacoco" @@ -44,38 +44,61 @@ dependencies { testImplementation "org.slf4j:slf4j-api:${slf4jVersion}" constraints { - implementation "com.fasterxml.jackson.core:jackson-databind:2.13.2" implementation "com.github.jknack:handlebars:4.2.0" implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "info.picocli:picocli:4.0.1" - implementation "io.swagger.core.v3:swagger-core:2.1.13" - implementation "io.swagger.core.v3:swagger-models:2.1.13" - implementation "io.swagger.parser.v3:swagger-parser-v2-converter:2.0.30" - implementation "io.swagger.parser.v3:swagger-parser:2.0.30" + implementation "io.swagger.core.v3:swagger-core:2.2.9" + implementation "io.swagger.core.v3:swagger-models:2.2.9" + implementation "io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}" implementation "javax.ws.rs:javax.ws.rs-api:2.1.1" 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}" testImplementation "org.testng:testng:${testngVersion}" } jacocoRuntime "org.jacoco:org.jacoco.agent:${jacoco.toolVersion}:runtime" - checkstyle project(":config:checkstyle") - checkstyle "com.puppycrawl.tools:checkstyle:${puppycrawlCheckstyleVersion}" + checkstyle project(':checkstyle') + checkstyle "com.puppycrawl.tools:checkstyle:${project.puppycrawlCheckstyleVersion}" } -sourceCompatibility = JavaVersion.VERSION_11 +sourceCompatibility = JavaVersion.VERSION_17 + +def excludePattern = '**/module-info.java' +tasks.withType(Checkstyle) { + exclude excludePattern +} + +checkstyle { + toolVersion "${project.puppycrawlCheckstyleVersion}" + configFile rootProject.file("config/checkstyle/build/checkstyle.xml") + configProperties = ["suppressionFile" : file("${rootDir}/config/checkstyle/build/suppressions.xml")] +} + +checkstyleMain.dependsOn(":checkstyle:downloadCheckstyleRuleFiles") +checkstyleMain.dependsOn(":checkstyle:compileTestJava") +checkstyleMain.dependsOn(":checkstyle:checkstyleMain") +checkstyleMain.dependsOn(":checkstyle:checkstyleTest") +checkstyleMain.dependsOn(":checkstyle:test") +checkstyleMain.dependsOn(":checkstyle:processTestResources") + +checkstyleTest.dependsOn(":checkstyle:downloadCheckstyleRuleFiles") +checkstyleTest.dependsOn(":checkstyle:compileTestJava") +checkstyleTest.dependsOn(":checkstyle:checkstyleMain") +checkstyleTest.dependsOn(":checkstyle:checkstyleTest") +checkstyleTest.dependsOn(":checkstyle:test") tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } jacoco { - toolVersion = "0.8.6" + toolVersion = "${project.jacocoVersion}" } test { @@ -119,7 +142,7 @@ spotbugsMain { effort = "max" reportLevel = "low" reportsDir = file("$project.buildDir/reports/spotbugs") - def excludeFile = file("spotbugs-exclude.xml") + def excludeFile = file("${rootDir}/spotbugs-exclude.xml") if (excludeFile.exists()) { it.excludeFilter = excludeFile } @@ -134,10 +157,8 @@ spotbugsTest { jacocoTestReport { reports { - xml.enabled true + xml.required = true } } spotbugsMain.finalizedBy validateSpotbugs -checkstyleMain.dependsOn(":config:checkstyle:downloadMultipleFiles") - diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index f3d88b1c2..033e24c4c 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ead7d724f..9f4197d5f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Fri Mar 22 16:42:38 IST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip \ No newline at end of file diff --git a/gradlew b/gradlew index 682b15725..fcb6fca14 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,126 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,93 +129,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi -exec "$JAVACMD" "$@" +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 6d57edc70..6689b85be 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,84 +1,92 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/module-ballerina-openapi/Ballerina.toml b/module-ballerina-openapi/Ballerina.toml index 8c781d0c3..49e3f3887 100644 --- a/module-ballerina-openapi/Ballerina.toml +++ b/module-ballerina-openapi/Ballerina.toml @@ -3,7 +3,7 @@ org= "ballerina" name= "openapi" version= "@toml.version@" -[[platform.java11.dependency]] +[[platform.java17.dependency]] path = "../openapi-validator/build/libs/openapi-validator-@project.version@.jar" groupId = "ballerina" artifactId = "openapi" diff --git a/module-ballerina-openapi/Package.md b/module-ballerina-openapi/Package.md index c5c7e4838..77139e86e 100644 --- a/module-ballerina-openapi/Package.md +++ b/module-ballerina-openapi/Package.md @@ -14,7 +14,7 @@ To report bugs, request new features, start new discussions, etc., go to the [op ### Useful Links * Discuss about code changes of the Ballerina project in [ballerina-dev@googlegroups.com](mailto:ballerina-dev@googlegroups.com). -* Chat live with us via our [Slack channel](https://ballerina.io/community/slack/). +* 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. * View the [Ballerina performance test results](performance/benchmarks/summary.md). diff --git a/module-ballerina-openapi/annotation.bal b/module-ballerina-openapi/annotation.bal index 2f4f17c64..bc425e057 100644 --- a/module-ballerina-openapi/annotation.bal +++ b/module-ballerina-openapi/annotation.bal @@ -36,5 +36,22 @@ public type ServiceInformation record {| string 'version?; |}; +// # Client configurations code. +// # + tags - OpenAPI tags that filter the openapi operations which need to be generated as client method +// # + operations - OpenAPI operationIds that filter the openapi operations which need to be generated as client method +// # + nullable - This enables to generate all data types in the record with Ballerina nil support +// # + isResource - Select client methods as resources for generation +// # + license - License path for adding license headers +// public type ClientConfiguration record {| +// string[]? tags = []; +// string[]? operations = []; +// boolean nullable = false; +// boolean isResource = true; +// string license = "// AUTO-GENERATED FILE. DO NOT MODIFY.\n\n " + +// "// This file is auto-generated by the Ballerina OpenAPI tool.\n"; +// |}; + # Annotation for additional OpenAPI information of a Ballerina service. public annotation ServiceInformation ServiceInfo on service; +// # Annotation for additional OpenAPI configurations of a Ballerina client. +// public const annotation ClientConfiguration ClientConfig on source client; diff --git a/module-ballerina-openapi/build.gradle b/module-ballerina-openapi/build.gradle index f9853792e..efee1502f 100644 --- a/module-ballerina-openapi/build.gradle +++ b/module-ballerina-openapi/build.gradle @@ -27,7 +27,9 @@ dependencies { } implementation project(':openapi-bal-service') implementation project(':openapi-validator') + implementation project(':openapi-core') implementation project(':openapi-cli') +// implementation project(':openapi-client-idl-plugin') implementation project(':openapi-ls-extension') implementation project(':openapi-extension') } @@ -46,7 +48,7 @@ jar { def packageName = "openapi" def packageOrg = "ballerina" -def platform = "java11" +def platform = "java17" def tomlVersion = stripBallerinaExtensionVersion("${project.version}") def ballerinaConfigFile = new File("$project.projectDir/Ballerina.toml") def ballerinaCompileConfigFile = new File("$project.projectDir/CompilerPlugin.toml") @@ -55,7 +57,10 @@ def artifactCacheParent = file("$project.projectDir/build/cache_parent/") def artifactLibParent = file("$project.projectDir/build/lib_parent/") def targetNativeJar = file("""$project.rootDir/${packageName}-validator/build/libs/${packageName}-validator-${project.version}.jar""") def targetOpenApiCommonJar = file("$project.rootDir/openapi-bal-service/build/libs/openapi-bal-service-${project.version}.jar") +def targetOpenApiCoreJar = file("$project.rootDir/openapi-core/build/libs/openapi-core-${project.version}.jar") def targetOpenApiCliJar = file("$project.rootDir/openapi-cli/build/libs/openapi-cli-${project.version}.jar") +//def targetOpenApiClientIDLJar = file("$project.rootDir/openapi-client-idl-plugin" + +// "/build/libs/openapi-client-idl-plugin-${project.version}.jar") def targetOpenApiBuiltInExtensionJar = file("$project.rootDir/openapi-extension/build/libs/openapi-extension-${project.version}.jar") def targetOpenApiBuildExtensionJar = file("$project.rootDir/openapi-build-extension/build/libs/openapi-build-extension-${project.version}.jar") def targetOpenApiLSJar = file("$project.rootDir/openapi-ls-extension/build/libs/openapi-ls-extension-${project.version}.jar") @@ -101,6 +106,7 @@ task unpackStdLibs() { task copyStdlibs(type: Copy) { def ballerinaDist = "build/target/extracted-distributions/jballerina-tools-zip/jballerina-tools-${ballerinaLangVersion}" into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE /* Standard Libraries */ configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> @@ -172,6 +178,7 @@ task initializeVariables { task ballerinaBuild { inputs.dir file(project.projectDir) + doNotTrackState("build needs to run every time") doLast { // Build and populate caches exec { @@ -210,6 +217,11 @@ task ballerinaBuild { into file("$artifactLibParent/libs") } + copy { + from targetOpenApiCoreJar + into file("$artifactLibParent/libs") + } + copy { from targetOpenApiCliJar into file("$artifactLibParent/libs") @@ -224,6 +236,12 @@ task ballerinaBuild { from targetOpenApiBuildExtensionJar into file("$artifactLibParent/libs") } + +// copy { +// from targetOpenApiClientIDLJar +// into file("$artifactLibParent/libs") +// } + copy { from targetOpenApiLSJar into file("$artifactLibParent/lslibs") @@ -321,6 +339,12 @@ ballerinaBuild.dependsOn ":${packageName}-extension:build" ballerinaBuild.dependsOn ":${packageName}-build-extension:build" ballerinaBuild.dependsOn updateCompilerTomlFile ballerinaBuild.dependsOn initializeVariables +ballerinaBuild.dependsOn generatePomFileForMavenJavaPublication +ballerinaBuild.dependsOn compileJava +ballerinaBuild.dependsOn compileTestJava +ballerinaBuild.dependsOn checkstyleMain +ballerinaBuild.dependsOn checkstyleTest +ballerinaBuild.dependsOn jar ballerinaBuild.finalizedBy revertTomlFile build.dependsOn ballerinaBuild diff --git a/openapi-bal-service/build.gradle b/openapi-bal-service/build.gradle index 394527a4c..7bcecca92 100644 --- a/openapi-bal-service/build.gradle +++ b/openapi-bal-service/build.gradle @@ -18,7 +18,7 @@ apply from: "$rootDir/gradle/javaProject.gradle" apply plugin: "com.github.johnrengelman.shadow" -apply plugin: "java" +apply plugin: "java-library" description = "Ballerina - OpenAPI Tooling - Ballerina to OpenAPI Command" @@ -31,20 +31,19 @@ configurations { } dependencies { - implementation "com.fasterxml.jackson.core:jackson-databind" - implementation "io.swagger.core.v3:swagger-models" - implementation ("io.swagger.parser.v3:swagger-parser-v2-converter") { + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { exclude group: "io.swagger", module: "swagger-compat-spec-parser" exclude group: "org.slf4j", module: "slf4j-ext" exclude group: "javax.validation", module: "validation-api" } - + implementation "io.swagger.core.v3:swagger-models" implementation "javax.ws.rs:javax.ws.rs-api" implementation "com.github.jknack:handlebars" implementation "info.picocli:picocli" implementation "org.ballerinalang:ballerina-lang" implementation "org.ballerinalang:ballerina-parser" implementation "org.ballerinalang:ballerina-tools-api" + implementation "org.ballerinalang:ballerina-runtime" implementation "org.eclipse.lsp4j:org.eclipse.lsp4j:0.8.1" implementation "com.google.code.findbugs:jsr305" @@ -84,6 +83,7 @@ task copyStdlibs(type: Copy) { dependsOn(unpackStdLibs) def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE /* Standard Libraries */ configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/Constants.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/Constants.java index 651b0cc40..88f63b674 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/Constants.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/Constants.java @@ -40,11 +40,13 @@ public class Constants { public static final String PATH = "path"; public static final String BODY = "body"; public static final String HTTP_PAYLOAD = "http:Payload"; + public static final String HTTP_QUERY = "http:Query"; public static final String HTTP = "http"; 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 BYTE = "byte"; public static final String OCTET_STREAM = "octet-stream"; public static final String XML = "xml"; public static final String JSON = "json"; @@ -135,6 +137,8 @@ public String toString() { Map httpCodeMap = new HashMap<>(); httpCodeMap.put("Continue", "100"); httpCodeMap.put("SwitchingProtocols", "101"); + httpCodeMap.put("Processing", "102"); + httpCodeMap.put("EarlyHints", "103"); httpCodeMap.put("Ok", "200"); httpCodeMap.put("Created", "201"); httpCodeMap.put("Accepted", "202"); @@ -142,6 +146,9 @@ public String toString() { httpCodeMap.put("NoContent", "204"); httpCodeMap.put("RestContent", "205"); httpCodeMap.put("PartialContent", "206"); + httpCodeMap.put("MultiStatus", "207"); + httpCodeMap.put("AlreadyReported", "208"); + httpCodeMap.put("IMUsed", "226"); httpCodeMap.put("MultipleChoices", "300"); httpCodeMap.put("MovedPermanently", "301"); httpCodeMap.put("Found", "302"); @@ -168,19 +175,37 @@ public String toString() { httpCodeMap.put("UnsupportedMediaType", "415"); httpCodeMap.put("RangeNotSatisfiable", "416"); httpCodeMap.put("ExpectationFailed", "417"); + httpCodeMap.put("MisdirectedRequest", "421"); + httpCodeMap.put("UnprocessableEntity", "422"); + httpCodeMap.put("Locked", "423"); + httpCodeMap.put("FailedDependency", "424"); + httpCodeMap.put("TooEarly", "425"); httpCodeMap.put("UpgradeRequired", "426"); + httpCodeMap.put("PreconditionRequired", "428"); httpCodeMap.put("TooManyRequests", "429"); httpCodeMap.put("RequestHeaderFieldsTooLarge", "431"); + httpCodeMap.put("UnavailableDueToLegalReasons", "451"); httpCodeMap.put("InternalServerError", "500"); httpCodeMap.put("NotImplemented", "501"); httpCodeMap.put("BadGateway", "502"); httpCodeMap.put("ServiceUnavailable", "503"); httpCodeMap.put("GatewayTimeOut", "504"); httpCodeMap.put("HttpVersionNotSupported", "505"); + httpCodeMap.put("VariantAlsoNegotiates", "506"); + httpCodeMap.put("InsufficientStorage", "507"); + httpCodeMap.put("LoopDetected", "508"); + httpCodeMap.put("NotExtended", "510"); + httpCodeMap.put("NetworkAuthenticationRequired", "511"); + httpCodeMap.put("NetworkAuthorizationRequired", "511"); //This status code was added since it is deprecated. + // TODO: remove this after fixing https://github.com/ballerina-platform/ballerina-standard-library/issues/4245 HTTP_CODES = Collections.unmodifiableMap(httpCodeMap); } public static final String HTTP_200 = "200"; + public static final String HTTP_201 = "201"; + public static final String HTTP_500 = "500"; public static final String HTTP_200_DESCRIPTION = "Ok"; + public static final String HTTP_201_DESCRIPTION = "Created"; + public static final String HTTP_500_DESCRIPTION = "Internal server error"; public static final String HTTP_204 = "204"; public static final String SPECIAL_CHAR_REGEX = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/\\_{}\\s|.$])"; diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/diagnostic/DiagnosticMessages.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/diagnostic/DiagnosticMessages.java index 4440862f7..4979795fe 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/diagnostic/DiagnosticMessages.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/diagnostic/DiagnosticMessages.java @@ -41,7 +41,7 @@ public enum DiagnosticMessages { DiagnosticSeverity.WARNING), OAS_CONVERTOR_106("OAS_CONVERTOR_106", "Given Ballerina file contains compilation error(s).", DiagnosticSeverity.ERROR), - OAS_CONVERTOR_107("OAS_CONVERTOR_107", "No Ballerina services found with name '%s' to" + + OAS_CONVERTOR_107("OAS_CONVERTOR_107", "No Ballerina HTTP services found with name '%s' to" + " generate an OpenAPI specification. These services are available in ballerina file. %s", DiagnosticSeverity.ERROR), OAS_CONVERTOR_108("OAS_CONVERTOR_108", "Failed to generate OpenAPI definition due to: %s", @@ -62,6 +62,10 @@ public enum DiagnosticMessages { OAS_CONVERTOR_114("OAS_CONVERTOR_114", "Generated OpenAPI definition does not contain information " + "for Ballerina type '%s'. ", DiagnosticSeverity.WARNING), OAS_CONVERTOR_115("OAS_CONVERTOR_115", "Failed to parser the Number value due to: %s ", + DiagnosticSeverity.ERROR), + "for Ballerina type '%s'. ", DiagnosticSeverity.WARNING), +//todo resolve conflicts + OAS_CONVERTOR_115("OAS_CONVERTOR_115", "Given Ballerina file does not contain any HTTP service.", DiagnosticSeverity.ERROR); private final String code; diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/model/OASGenerationMetaInfo.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/model/OASGenerationMetaInfo.java new file mode 100644 index 000000000..6f9f7a415 --- /dev/null +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/model/OASGenerationMetaInfo.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. + * + * 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.openapi.converter.model; + +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.projects.Project; + +import java.nio.file.Path; + +/** + * This {@code OASGenerationMetaInfo} contains details related to openAPI specification. + * + * @since 1.6.0 + */ +public class OASGenerationMetaInfo { + + private final String openApiFileName; + private final Path ballerinaFilePath; + private final SemanticModel semanticModel; + private final ServiceDeclarationNode serviceDeclarationNode; + private final Project project; + + public OASGenerationMetaInfo(OASGenerationMetaInfoBuilder builder) { + this.openApiFileName = builder.openApiFileName; + this.ballerinaFilePath = builder.ballerinaFilePath; + this.semanticModel = builder.semanticModel; + this.serviceDeclarationNode = builder.serviceDeclarationNode; + this.project = builder.project; + } + + public String getOpenApiFileName() { + return openApiFileName; + } + + public Path getBallerinaFilePath() { + return ballerinaFilePath; + } + + public SemanticModel getSemanticModel() { + return semanticModel; + } + + public ServiceDeclarationNode getServiceDeclarationNode() { + return serviceDeclarationNode; + } + + public Project getProject() { + return project; + } + + /** + * This method is used to create a new {@link OASGenerationMetaInfoBuilder} instance. + */ + public static class OASGenerationMetaInfoBuilder { + + private String openApiFileName; + private Path ballerinaFilePath; + private SemanticModel semanticModel; + private ServiceDeclarationNode serviceDeclarationNode; + private Project project; + + public OASGenerationMetaInfoBuilder setBallerinaFilePath(Path ballerinaFilePath) { + this.ballerinaFilePath = ballerinaFilePath; + return this; + } + + public OASGenerationMetaInfoBuilder setSemanticModel(SemanticModel semanticModel) { + this.semanticModel = semanticModel; + return this; + } + + public OASGenerationMetaInfoBuilder setServiceDeclarationNode(ServiceDeclarationNode serviceDeclarationNode) { + this.serviceDeclarationNode = serviceDeclarationNode; + return this; + } + + public OASGenerationMetaInfoBuilder setOpenApiFileName(String openApiFileName) { + this.openApiFileName = openApiFileName; + return this; + } + + public Project setProject(Project project) { + this.project = project; + return project; + } + + public OASGenerationMetaInfo build() { + return new OASGenerationMetaInfo(this); + } + } +} diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/ModuleMemberVisitor.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/ModuleMemberVisitor.java new file mode 100644 index 000000000..252325a26 --- /dev/null +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/ModuleMemberVisitor.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.converter.service; + +import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; +import io.ballerina.compiler.syntax.tree.NodeVisitor; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; + +import java.util.LinkedList; +import java.util.List; + +/** + * Visitor to get the TypeDefinitionNode and ListenerDeclarationNodes. + * + * @since 1.6.0 + */ +public class ModuleMemberVisitor extends NodeVisitor { + + LinkedList typeDefinitionNodes = new LinkedList<>(); + LinkedList listenerDeclarationNodes = new LinkedList<>(); + + @Override + public void visit(TypeDefinitionNode typeDefinitionNode) { + typeDefinitionNodes.add(typeDefinitionNode); + } + + @Override + public void visit(ListenerDeclarationNode listenerDeclarationNode) { + listenerDeclarationNodes.add(listenerDeclarationNode); + } + + public List getTypeDefinitionNodes() { + return typeDefinitionNodes; + } + + public List getListenerDeclarationNodes() { + return listenerDeclarationNodes; + } +} diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIComponentMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIComponentMapper.java index 9404d9b2b..32c5e155a 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIComponentMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIComponentMapper.java @@ -78,6 +78,8 @@ import static io.ballerina.openapi.converter.Constants.DOUBLE; import static io.ballerina.openapi.converter.Constants.FLOAT; +import static io.ballerina.openapi.converter.Constants.HTTP; +import static io.ballerina.openapi.converter.Constants.HTTP_CODES; /** * This util class for processing the mapping in between ballerina record and openAPI object schema. @@ -88,7 +90,7 @@ public class OpenAPIComponentMapper { private final Components components; private final List diagnostics; private final NonTerminalNode rootNode; - + private final HashSet visitedTypeDefinitionNames = new HashSet<>(); public OpenAPIComponentMapper(Components components, NonTerminalNode rootNode) { @@ -100,11 +102,12 @@ public OpenAPIComponentMapper(Components components, NonTerminalNode rootNode) { public List getDiagnostics() { return diagnostics; } + /** * This function for doing the mapping with ballerina record to object schema. * - * @param schema Map of current schemas - * @param typeSymbol Record Name as a TypeSymbol + * @param schema Map of current schemas + * @param typeSymbol Record Name as a TypeSymbol */ public void createComponentSchema(Map schema, TypeSymbol typeSymbol) { if (schema == null) { @@ -121,14 +124,9 @@ public void createComponentSchema(Map schema, TypeSymbol typeSym TypeSymbol type = typeRef.typeDescriptor(); // Handle record type request body if (type.typeKind() == TypeDescKind.INTERSECTION) { - List typeSymbols = ((IntersectionTypeSymbol) type).memberTypeDescriptors(); - for (TypeSymbol symbol: typeSymbols) { - if (!(symbol instanceof ReadonlyTypeSymbol)) { - type = symbol; - break; - } - } + type = excludeReadonlyIfPresent(type); } + //Access module part node for finding the node to given typeSymbol. //TODO: this works for module reference. ModulePartNode modulePartNode = rootNode.syntaxTree().rootNode(); @@ -149,11 +147,26 @@ public void createComponentSchema(Map schema, TypeSymbol typeSym // Handle typeInclusions with allOf type binding handleRecordTypeSymbol((RecordTypeSymbol) type, schema, componentName, apiDocs); break; + case TYPE_REFERENCE: + schema.put(componentName, new ObjectSchema().$ref(ConverterCommonUtils.unescapeIdentifier( + type.getName().orElseThrow().trim()))); + components.setSchemas(schema); + TypeReferenceTypeSymbol referredType = (TypeReferenceTypeSymbol) type; + if (!visitedTypeDefinitionNames.contains(componentName)) { + visitedTypeDefinitionNames.add(componentName); + createComponentSchema(schema, referredType); + } + break; case STRING: schema.put(componentName, setConstraintValueToSchema(constraintAnnot, new StringSchema().description(typeDoc))); components.setSchemas(schema); break; + case JSON: + case XML: + schema.put(componentName, new ObjectSchema().description(typeDoc)); + components.setSchemas(schema); + break; case INT: schema.put(componentName, setConstraintValueToSchema(constraintAnnot, new IntegerSchema().description(typeDoc))); @@ -177,18 +190,41 @@ public void createComponentSchema(Map schema, TypeSymbol typeSym components.setSchemas(schema); break; case UNION: - Schema unionSchema = handleUnionType((UnionTypeSymbol) type, new Schema<>(), componentName); - schema.put(componentName, unionSchema.description(typeDoc)); - components.setSchemas(schema); + if (!visitedTypeDefinitionNames.contains(componentName)) { + visitedTypeDefinitionNames.add(componentName); + if (typeRef.definition() instanceof EnumSymbol) { + EnumSymbol enumSymbol = (EnumSymbol) typeRef.definition(); + Schema enumSchema = mapEnumValues(enumSymbol); + schema.put(componentName, enumSchema.description(typeDoc)); + } else { + Schema unionSchema = handleUnionType((UnionTypeSymbol) type, new Schema<>(), componentName); + schema.put(componentName, unionSchema.description(typeDoc)); + } + if (components.getSchemas() != null) { + schema.putAll(components.getSchemas()); + } + components.setSchemas(schema); + } break; case MAP: MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) type; - TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); - Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(typeDescKind.getName()); - schema.put(componentName, - new ObjectSchema().additionalProperties( - openApiSchema.getType() == null ? true : openApiSchema) - .description(typeDoc)); + TypeSymbol typeParam = mapTypeSymbol.typeParam(); + + if (typeParam.typeKind() == TypeDescKind.TYPE_REFERENCE) { + TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) typeParam; + schema.put(componentName, new ObjectSchema().additionalProperties(new ObjectSchema() + .$ref(ConverterCommonUtils.unescapeIdentifier( + typeReferenceTypeSymbol.getName().orElseThrow().trim())))); + createComponentSchema(schema, typeReferenceTypeSymbol); + } + + if (!schema.containsKey(componentName)) { + TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); + Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(typeDescKind.getName()); + schema.put(componentName, new ObjectSchema().additionalProperties( + openApiSchema.getType() == null ? true : openApiSchema).description(typeDoc)); + } + Map schemas = components.getSchemas(); if (schemas != null) { schemas.putAll(schema); @@ -206,16 +242,33 @@ public void createComponentSchema(Map schema, TypeSymbol typeSym } } + /** + * Remove readonly from the type symbol. + * + * @param typeSymbol TypeSymbol + * @return typeSymbol without readonly + */ + public TypeSymbol excludeReadonlyIfPresent(TypeSymbol typeSymbol) { + List typeSymbols = ((IntersectionTypeSymbol) typeSymbol).memberTypeDescriptors(); + for (TypeSymbol symbol : typeSymbols) { + if (!(symbol instanceof ReadonlyTypeSymbol)) { + typeSymbol = symbol; + break; + } + } + return typeSymbol; + } + private void handleRecordTypeSymbol(RecordTypeSymbol recordTypeSymbol, Map schema, String componentName, Map apiDocs) { // Handle typeInclusions with allOf type binding + visitedTypeDefinitionNames.add(componentName); List typeInclusions = recordTypeSymbol.typeInclusions(); Map rfields = recordTypeSymbol.fieldDescriptors(); - HashSet unionKeys = new HashSet<>(rfields.keySet()); if (typeInclusions.isEmpty()) { generateObjectSchemaFromRecordFields(schema, componentName, rfields, apiDocs); } else { - mapTypeInclusionToAllOfSchema(schema, componentName, typeInclusions, rfields, unionKeys, apiDocs); + mapTypeInclusionToAllOfSchema(schema, componentName, recordTypeSymbol, apiDocs); } } @@ -223,8 +276,7 @@ private void handleRecordTypeSymbol(RecordTypeSymbol recordTypeSymbol, Map getRecordFieldsAPIDocsMap(TypeReferenceTypeSymbol typeSymbol, String componentName) { - - Map apiDocs = new LinkedHashMap<>(); + Map apiDocs = new LinkedHashMap<>(); Symbol recordSymbol = typeSymbol.definition(); Optional documentation = ((Documentable) recordSymbol).documentation(); if (documentation.isPresent() && documentation.get().description().isPresent()) { @@ -232,15 +284,17 @@ private Map getRecordFieldsAPIDocsMap(TypeReferenceTypeSymbol ty apiDocs.put(componentName, description.get().trim()); } // Record field apidoc mapping - TypeDefinitionSymbol recordTypeDefinitionSymbol = (TypeDefinitionSymbol) ((typeSymbol).definition()); - if (recordTypeDefinitionSymbol.typeDescriptor() instanceof RecordTypeSymbol) { - RecordTypeSymbol recordType = (RecordTypeSymbol) recordTypeDefinitionSymbol.typeDescriptor(); - Map recordFieldSymbols = recordType.fieldDescriptors(); - for (Map.Entry fields: recordFieldSymbols.entrySet()) { - Optional fieldDoc = ((Documentable) fields.getValue()).documentation(); - if (fieldDoc.isPresent() && fieldDoc.get().description().isPresent()) { - apiDocs.put(ConverterCommonUtils.unescapeIdentifier(fields.getKey()), - fieldDoc.get().description().get()); + if (((typeSymbol).definition() instanceof TypeDefinitionSymbol)) { + TypeDefinitionSymbol recordTypeDefinitionSymbol = (TypeDefinitionSymbol) ((typeSymbol).definition()); + if (recordTypeDefinitionSymbol.typeDescriptor() instanceof RecordTypeSymbol) { + RecordTypeSymbol recordType = (RecordTypeSymbol) recordTypeDefinitionSymbol.typeDescriptor(); + Map recordFieldSymbols = recordType.fieldDescriptors(); + for (Map.Entry fields : recordFieldSymbols.entrySet()) { + Optional fieldDoc = ((Documentable) fields.getValue()).documentation(); + if (fieldDoc.isPresent() && fieldDoc.get().description().isPresent()) { + apiDocs.put(ConverterCommonUtils.unescapeIdentifier(fields.getKey()), + fieldDoc.get().description().get()); + } } } } @@ -250,26 +304,29 @@ private Map getRecordFieldsAPIDocsMap(TypeReferenceTypeSymbol ty /** * This function is to map the ballerina typeInclusion to OAS allOf composedSchema. */ - private void mapTypeInclusionToAllOfSchema(Map schema, - String componentName, List typeInclusions, Map rfields, HashSet unionKeys, Map apiDocs) { + private void mapTypeInclusionToAllOfSchema(Map schema, String componentName, + RecordTypeSymbol recordTypeSymbol, Map apiDocs) { + List typeInclusions = recordTypeSymbol.typeInclusions(); + Map recordFields = recordTypeSymbol.fieldDescriptors(); + HashSet recordFieldNames = new HashSet<>(recordFields.keySet()); // Map to allOF need to check the status code inclusion there ComposedSchema allOfSchema = new ComposedSchema(); // Set schema List allOfSchemaList = new ArrayList<>(); - for (TypeSymbol typeInclusion: typeInclusions) { + for (TypeSymbol typeInclusion : typeInclusions) { Schema referenceSchema = new Schema(); String typeInclusionName = typeInclusion.getName().orElseThrow(); referenceSchema.set$ref(ConverterCommonUtils.unescapeIdentifier(typeInclusionName)); allOfSchemaList.add(referenceSchema); if (typeInclusion.typeKind().equals(TypeDescKind.TYPE_REFERENCE)) { TypeReferenceTypeSymbol typeRecord = (TypeReferenceTypeSymbol) typeInclusion; - if (typeRecord.typeDescriptor() instanceof RecordTypeSymbol) { + if (typeRecord.typeDescriptor() instanceof RecordTypeSymbol && + !isSameRecord(typeInclusionName, typeRecord)) { RecordTypeSymbol typeInclusionRecord = (RecordTypeSymbol) typeRecord.typeDescriptor(); Map tInFields = typeInclusionRecord.fieldDescriptors(); - unionKeys.addAll(tInFields.keySet()); - unionKeys.removeAll(tInFields.keySet()); + recordFieldNames.addAll(tInFields.keySet()); + recordFieldNames.removeAll(tInFields.keySet()); generateObjectSchemaFromRecordFields(schema, typeInclusionName, tInFields, apiDocs); // Update the schema value schema = this.components.getSchemas(); @@ -277,7 +334,7 @@ private void mapTypeInclusionToAllOfSchema(Map schema, } } Map filteredField = new LinkedHashMap<>(); - rfields.forEach((key1, value) -> unionKeys.stream().filter(key -> + recordFields.forEach((key1, value) -> recordFieldNames.stream().filter(key -> ConverterCommonUtils.unescapeIdentifier(key1.trim()). equals(ConverterCommonUtils.unescapeIdentifier(key))).forEach(key -> filteredField.put(ConverterCommonUtils.unescapeIdentifier(key1), value))); @@ -287,6 +344,9 @@ private void mapTypeInclusionToAllOfSchema(Map schema, if (schema != null && !schema.containsKey(componentName)) { // Set properties for the schema schema.put(componentName, allOfSchema); + if (this.components.getSchemas() != null) { + schema.putAll(this.components.getSchemas()); + } this.components.setSchemas(schema); } else if (schema == null) { schema = new LinkedHashMap<>(); @@ -329,12 +389,19 @@ private ObjectSchema generateObjectSchemaFromRecordFields(Map sc } TypeDescKind fieldTypeKind = field.getValue().typeDescriptor().typeKind(); String type = fieldTypeKind.toString().toLowerCase(Locale.ENGLISH); + + if (fieldTypeKind == TypeDescKind.INTERSECTION) { + TypeSymbol readOnlyExcludedType = excludeReadonlyIfPresent(field.getValue().typeDescriptor()); + type = readOnlyExcludedType.typeKind().toString().toLowerCase(Locale.ENGLISH); + } + Schema property = ConverterCommonUtils.getOpenApiSchema(type); if (fieldTypeKind == TypeDescKind.TYPE_REFERENCE) { TypeReferenceTypeSymbol typeReference = (TypeReferenceTypeSymbol) field.getValue().typeDescriptor(); - property = handleTypeReference(schema, typeReference, property, isSameRecord(componentName, - typeReference)); + property = handleTypeReference(schema, typeReference, property, + isSameRecord(ConverterCommonUtils.unescapeIdentifier( + typeReference.definition().getName().get()), typeReference)); schema = components.getSchemas(); } else if (fieldTypeKind == TypeDescKind.UNION) { property = handleUnionType((UnionTypeSymbol) field.getValue().typeDescriptor(), property, @@ -364,17 +431,21 @@ private ObjectSchema generateObjectSchemaFromRecordFields(Map sc if (componentName != null && schema != null && !schema.containsKey(componentName)) { // Set properties for the schema schema.put(componentName, componentSchema); + if (this.components.getSchemas() != null) { + schema.putAll(this.components.getSchemas()); + } this.components.setSchemas(schema); } else if (schema == null && componentName != null) { schema = new LinkedHashMap<>(); schema.put(componentName, componentSchema); this.components.setSchemas(schema); } + visitedTypeDefinitionNames.add(componentName); return componentSchema; } private Schema handleMapType(Map schema, String componentName, Schema property, - MapTypeSymbol mapTypeSymbol) { + MapTypeSymbol mapTypeSymbol) { TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); if (typeDescKind == TypeDescKind.TYPE_REFERENCE) { @@ -396,7 +467,7 @@ private Schema handleMapType(Map schema, String componentName, S * This function uses to handle the field datatype has TypeReference(ex: Record or Enum). */ private Schema handleTypeReference(Map schema, TypeReferenceTypeSymbol typeReferenceSymbol, - Schema property, boolean isCyclicRecord) { + Schema property, boolean isCyclicRecord) { if (typeReferenceSymbol.definition().kind() == SymbolKind.ENUM) { EnumSymbol enumSymbol = (EnumSymbol) typeReferenceSymbol.definition(); property = mapEnumValues(enumSymbol); @@ -422,16 +493,23 @@ private Schema handleUnionType(UnionTypeSymbol unionType, Schema property, Strin List unionTypes = unionType.memberTypeDescriptors(); List properties = new ArrayList<>(); boolean nullable = false; - for (TypeSymbol union: unionTypes) { + for (TypeSymbol union : unionTypes) { + if (union.typeKind() == TypeDescKind.INTERSECTION) { + union = excludeReadonlyIfPresent(union); + } if (union.typeKind() == TypeDescKind.NIL) { nullable = true; } else if (union.typeKind() == TypeDescKind.TYPE_REFERENCE) { + if (union.getModule().isPresent() && union.getModule().get().id().modulePrefix().equals(HTTP) && + union.getName().isPresent() && HTTP_CODES.containsKey(union.getName().get())) { + continue; + } property = ConverterCommonUtils.getOpenApiSchema(union.typeKind().getName().trim()); TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) union; - property = handleTypeReference(this.components.getSchemas(), typeReferenceTypeSymbol, property, + property = handleTypeReference(components.getSchemas(), typeReferenceTypeSymbol, property, isSameRecord(parentComponentName, typeReferenceTypeSymbol)); + visitedTypeDefinitionNames.add(typeReferenceTypeSymbol.getName().get()); 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); properties.add(property); @@ -444,9 +522,10 @@ private Schema handleUnionType(UnionTypeSymbol unionType, Schema property, Strin Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(typeDescKind.getName()); property = new ObjectSchema().additionalProperties(openApiSchema); properties.add(property); - Map schemas = components.getSchemas(); - if (schemas != null) { - schemas.put(parentComponentName, property);; + if (components.getSchemas() != null) { + Map schemas = components.getSchemas(); + schemas.put(parentComponentName, property); + components.setSchemas(schemas); } else { Map schema = new HashMap<>(); schema.put(parentComponentName, property); @@ -457,7 +536,6 @@ private Schema handleUnionType(UnionTypeSymbol unionType, Schema property, Strin properties.add(property); } } - property = generateOneOfSchema(property, properties); if (nullable) { property.setNullable(true); @@ -469,8 +547,7 @@ private boolean isSameRecord(String parentComponentName, TypeReferenceTypeSymbol if (parentComponentName == null) { return false; } - return typeReferenceTypeSymbol.getName().isPresent() && - parentComponentName.equals(typeReferenceTypeSymbol.getName().get().trim()); + return visitedTypeDefinitionNames.contains(typeReferenceTypeSymbol.getName().get().trim()); } /** @@ -511,7 +588,8 @@ private Schema mapEnumValues(EnumSymbol enumSymbol) { * Generate arraySchema for ballerina record as array type. */ private ArraySchema mapArrayToArraySchema(Map schema, TypeSymbol symbol, - String componentName) { + String componentName) { + visitedTypeDefinitionNames.add(componentName); ArraySchema property = new ArraySchema(); int arrayDimensions = 0; while (symbol instanceof ArrayTypeSymbol) { @@ -520,7 +598,7 @@ private ArraySchema mapArrayToArraySchema(Map schema, TypeSymbol symbol = arrayTypeSymbol.memberTypeDescriptor(); } // Handle record fields have reference record array type (ex: Tag[] tags) - Schema symbolProperty = ConverterCommonUtils.getOpenApiSchema(symbol.typeKind().getName()); + Schema symbolProperty = ConverterCommonUtils.getOpenApiSchema(symbol.typeKind().getName()); // Handle record fields have union type array (ex: string[]? name) if (symbol.typeKind() == TypeDescKind.UNION) { symbolProperty = getSchemaForUnionType((UnionTypeSymbol) symbol, symbolProperty, componentName, schema); @@ -565,7 +643,7 @@ private ArraySchema mapArrayToArraySchema(Map schema, TypeSymbol /** * 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 OAS. @@ -573,7 +651,7 @@ private ArraySchema mapArrayToArraySchema(Map schema, TypeSymbol private Schema getSchemaForUnionType(UnionTypeSymbol symbol, Schema symbolProperty, String componentName, Map schema) { List typeSymbols = symbol.userSpecifiedMemberTypes(); - for (TypeSymbol typeSymbol: typeSymbols) { + for (TypeSymbol typeSymbol : typeSymbols) { if (typeSymbol.typeKind() == TypeDescKind.ARRAY) { TypeSymbol arrayType = ((ArrayTypeSymbol) typeSymbol).memberTypeDescriptor(); // Set the record model to the definition @@ -592,17 +670,17 @@ private Schema getSchemaForUnionType(UnionTypeSymbol symbol, Schema symbolProper /** * This util function is to handle the type reference symbol is record type or enum type. */ - private Schema getSchemaForTypeReferenceSymbol(TypeSymbol arrayType, Schema symbolProperty, String componentName, - Map schema) { + private Schema getSchemaForTypeReferenceSymbol(TypeSymbol referenceType, Schema symbolProperty, + String componentName, Map schema) { - if (((TypeReferenceTypeSymbol) arrayType).definition().kind() == SymbolKind.ENUM) { - TypeReferenceTypeSymbol typeRefEnum = (TypeReferenceTypeSymbol) arrayType; + if (((TypeReferenceTypeSymbol) referenceType).definition().kind() == SymbolKind.ENUM) { + TypeReferenceTypeSymbol typeRefEnum = (TypeReferenceTypeSymbol) referenceType; EnumSymbol enumSymbol = (EnumSymbol) typeRefEnum.definition(); symbolProperty = mapEnumValues(enumSymbol); } else { symbolProperty.set$ref(ConverterCommonUtils.unescapeIdentifier( - arrayType.getName().orElseThrow().trim())); - TypeReferenceTypeSymbol typeRecord = (TypeReferenceTypeSymbol) arrayType; + referenceType.getName().orElseThrow().trim())); + TypeReferenceTypeSymbol typeRecord = (TypeReferenceTypeSymbol) referenceType; if (!isSameRecord(componentName, typeRecord)) { createComponentSchema(schema, typeRecord); } @@ -616,7 +694,7 @@ private Schema getSchemaForTypeReferenceSymbol(TypeSymbol arrayType, Schema symb private ArraySchema handleArray(int arrayDimensions, Schema property, ArraySchema arrayProperty) { if (arrayDimensions > 1) { ArraySchema narray = new ArraySchema(); - arrayProperty.setItems(handleArray(arrayDimensions - 1, property, narray)); + arrayProperty.setItems(handleArray(arrayDimensions - 1, property, narray)); } else if (arrayDimensions == 1) { arrayProperty.setItems(property); } diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java index f9d9d260f..fa18fd196 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIEndpointMapper.java @@ -31,6 +31,7 @@ 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.QualifiedNameReferenceNode; import io.ballerina.compiler.syntax.tree.SeparatedNodeList; import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; import io.ballerina.compiler.syntax.tree.SpecificFieldNode; @@ -44,6 +45,7 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; @@ -64,22 +66,18 @@ public class OpenAPIEndpointMapper { * @param service service node with bound endpoints * @return openapi definition with Server information */ - public OpenAPI getServers(OpenAPI openAPI, List endpoints, + public OpenAPI getServers(OpenAPI openAPI, LinkedHashSet endpoints, ServiceDeclarationNode service) { openAPI = extractServerForExpressionNode(openAPI, service.expressions(), service); List servers = openAPI.getServers(); + //Handle ImplicitNewExpressionNode in listener 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); - Server server = extractServer(ep, serviceBasePath); - servers.add(server); - } + updateServerDetails(service, servers, ep, node); } } - } if (servers.size() > 1) { Server mainServer = addEnumValues(servers); @@ -88,6 +86,27 @@ public OpenAPI getServers(OpenAPI openAPI, List endpoin return openAPI; } + /** + * This util is for extracting the server details from endpoints and update server list. + */ + private void updateServerDetails(ServiceDeclarationNode service, List servers, + ListenerDeclarationNode endPoint, ExpressionNode expNode) { + + if (expNode instanceof QualifiedNameReferenceNode) { + //Handle QualifiedNameReferenceNode in listener + QualifiedNameReferenceNode refNode = (QualifiedNameReferenceNode) expNode; + if (refNode.identifier().text().trim().equals(endPoint.variableName().text().trim())) { + String serviceBasePath = getServiceBasePath(service); + Server server = extractServer(endPoint, serviceBasePath); + servers.add(server); + } + } else if (expNode.toString().trim().equals(endPoint.variableName().text().trim())) { + String serviceBasePath = getServiceBasePath(service); + Server server = extractServer(endPoint, serviceBasePath); + servers.add(server); + } + } + private Server addEnumValues(List servers) { Server mainServer = servers.get(0); @@ -136,7 +155,7 @@ private Optional extractListenerNodeType(Node expression2) return list; } - // Function for handle both ExplicitNewExpressionNode and ImplicitNewExpressionNode in listener. + // Function to handle ExplicitNewExpressionNode in listener. private OpenAPI extractServerForExpressionNode(OpenAPI openAPI, SeparatedNodeList bTypeExplicit, ServiceDeclarationNode service) { String serviceBasePath = getServiceBasePath(service); @@ -148,11 +167,6 @@ private OpenAPI extractServerForExpressionNode(OpenAPI openAPI, SeparatedNodeLis list = Optional.ofNullable(explicit.parenthesizedArgList()); Server server = generateServer(serviceBasePath, list); servers.add(server); - } else if (expressionNode.kind().equals(SyntaxKind.IMPLICIT_NEW_EXPRESSION)) { - ImplicitNewExpressionNode implicit = (ImplicitNewExpressionNode) expressionNode; - list = implicit.parenthesizedArgList(); - Server server = generateServer(serviceBasePath, list); - servers.add(server); } } openAPI.setServers(servers); diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIHeaderMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIHeaderMapper.java index f4aea4d5d..70466d441 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIHeaderMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIHeaderMapper.java @@ -17,6 +17,7 @@ */ package io.ballerina.openapi.converter.service; +import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; @@ -24,13 +25,16 @@ 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.OptionalTypeDescriptorNode; 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.SimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.SpecificFieldNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.openapi.converter.Constants; import io.ballerina.openapi.converter.utils.ConverterCommonUtils; +import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.HeaderParameter; @@ -43,6 +47,7 @@ import java.util.Optional; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.getAnnotationNodesFromServiceNode; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.handleReference; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.unescapeIdentifier; /** @@ -51,10 +56,14 @@ * @since 2.0.0 */ public class OpenAPIHeaderMapper { + private final Components components; + private final SemanticModel semanticModel; private final Map apidocs; - public OpenAPIHeaderMapper(Map apidocs) { + public OpenAPIHeaderMapper(Components components, SemanticModel semanticModel, Map apidocs) { this.apidocs = apidocs; + this.components = components; + this.semanticModel = semanticModel; } /** @@ -67,9 +76,21 @@ public List setHeaderParameter(RequiredParameterNode headerParam) { String headerName = unescapeIdentifier(extractHeaderName(headerParam)); HeaderParameter headerParameter = new HeaderParameter(); Node node = headerParam.typeName(); - Schema headerTypeSchema = ConverterCommonUtils.getOpenApiSchema(getHeaderType(headerParam)); + Schema headerTypeSchema; + String isOptional = Constants.FALSE; + Node headerDetailNode = headerParam.typeName(); + if (headerParam.typeName().kind() == SyntaxKind.OPTIONAL_TYPE_DESC) { + headerDetailNode = ((OptionalTypeDescriptorNode) headerParam.typeName()).typeDescriptor(); + isOptional = Constants.TRUE; + } + + if (headerDetailNode.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode refNode = (SimpleNameReferenceNode) headerDetailNode; + headerTypeSchema = handleReference(semanticModel, components, refNode); + } else { + headerTypeSchema = ConverterCommonUtils.getOpenApiSchema(getHeaderType(headerParam)); + } NodeList annotations = getAnnotationNodesFromServiceNode(headerParam); - String isOptional = Constants.TRUE; if (!annotations.isEmpty()) { Optional values = ConverterCommonUtils.extractServiceAnnotationDetails(annotations, "http:ServiceConfig", "treatNilableAsOptional"); @@ -82,7 +103,7 @@ public List setHeaderParameter(RequiredParameterNode headerParam) { headerParameter.setDescription(apidocs.get(headerName.trim())); } completeHeaderParameter(parameters, headerName, headerParameter, headerTypeSchema, headerParam.annotations(), - headerParam.typeName()); + headerDetailNode); return parameters; } @@ -102,7 +123,13 @@ public List setHeaderParameter(DefaultableParameterNode headerParam) List parameters = new ArrayList<>(); String headerName = extractHeaderName(headerParam); HeaderParameter headerParameter = new HeaderParameter(); - Schema headerTypeSchema = ConverterCommonUtils.getOpenApiSchema(getHeaderType(headerParam)); + Schema headerTypeSchema; + if (headerParam.typeName().kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode refNode = (SimpleNameReferenceNode) headerParam.typeName(); + headerTypeSchema = handleReference(semanticModel, components, refNode); + } else { + headerTypeSchema = ConverterCommonUtils.getOpenApiSchema(getHeaderType(headerParam)); + } String defaultValue = headerParam.expression().toString().trim(); if (defaultValue.length() > 1 && defaultValue.charAt(0) == '"' && defaultValue.charAt(defaultValue.length() - 1) == '"') { @@ -154,7 +181,13 @@ private void completeHeaderParameter(List parameters, String headerNa ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) node; ArraySchema arraySchema = new ArraySchema(); SyntaxKind kind = arrayNode.memberTypeDesc().kind(); - Schema itemSchema = ConverterCommonUtils.getOpenApiSchema(kind); + Schema itemSchema; + if (kind == SyntaxKind.SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode refNode = (SimpleNameReferenceNode) arrayNode.memberTypeDesc(); + itemSchema = handleReference(semanticModel, components, refNode); + } else { + itemSchema = ConverterCommonUtils.getOpenApiSchema(kind); + } if (headerSchema.getDefault() != null) { arraySchema.setDefault(headerSchema.getDefault()); } diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIParameterMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIParameterMapper.java index b8d302fc4..6b137ea9b 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIParameterMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIParameterMapper.java @@ -195,8 +195,13 @@ private void handleAnnotationParameters(Components components, for (AnnotationNode annotation: annotations) { if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_HEADER)) { // Handle headers. - OpenAPIHeaderMapper openAPIHeaderMapper = new OpenAPIHeaderMapper(apidocs); + OpenAPIHeaderMapper openAPIHeaderMapper = new OpenAPIHeaderMapper(components, semanticModel, apidocs); parameters.addAll(openAPIHeaderMapper.setHeaderParameter(requiredParameterNode)); + } else if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_QUERY)) { + // Handle query parameter. + OpenAPIQueryParameterMapper openAPIQueryParameterMapper = new OpenAPIQueryParameterMapper(apidocs, + components, semanticModel); + parameters.add(openAPIQueryParameterMapper.createQueryParameter(requiredParameterNode)); } else if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_PAYLOAD) && (!Constants.GET.toLowerCase(Locale.ENGLISH).equalsIgnoreCase( operationAdaptor.getHttpOperation()))) { @@ -228,8 +233,13 @@ private List handleDefaultableAnnotationParameters(DefaultableParamet for (AnnotationNode annotation: annotations) { if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_HEADER)) { // Handle headers. - OpenAPIHeaderMapper openAPIHeaderMapper = new OpenAPIHeaderMapper(apidocs); + OpenAPIHeaderMapper openAPIHeaderMapper = new OpenAPIHeaderMapper(components, semanticModel, apidocs); parameters = openAPIHeaderMapper.setHeaderParameter(defaultableParameterNode); + } else if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_QUERY)) { + // Handle query parameter. + OpenAPIQueryParameterMapper openAPIQueryParameterMapper = new OpenAPIQueryParameterMapper(apidocs, + components, semanticModel); + parameters.add(openAPIQueryParameterMapper.createQueryParameter(defaultableParameterNode)); } } return parameters; diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIQueryParameterMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIQueryParameterMapper.java index e2e93d46a..39275a4d9 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIQueryParameterMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIQueryParameterMapper.java @@ -51,10 +51,13 @@ 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.SIMPLE_NAME_REFERENCE; import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_LITERAL; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.getAnnotationNodesFromServiceNode; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.handleReference; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.unescapeIdentifier; + /** * This class processes mapping query parameters in between Ballerina and OAS. * @@ -83,7 +86,7 @@ public Parameter createQueryParameter(RequiredParameterNode queryParam) { && queryParam.annotations().isEmpty(); if (queryParam.typeName() instanceof BuiltinSimpleNameReferenceNode && isQuery) { QueryParameter queryParameter = new QueryParameter(); - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(queryParam.typeName().toString().trim()); queryParameter.setSchema(openApiSchema); queryParameter.setRequired(true); @@ -110,19 +113,29 @@ public Parameter createQueryParameter(RequiredParameterNode queryParam) { return handleArrayTypeQueryParameter(queryParamName, arrayNode); } else if (queryParam.typeName() instanceof SimpleNameReferenceNode && isQuery) { QueryParameter queryParameter = new QueryParameter(); - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); SimpleNameReferenceNode queryNode = (SimpleNameReferenceNode) queryParam.typeName(); OpenAPIComponentMapper componentMapper = new OpenAPIComponentMapper(components, queryNode); TypeSymbol typeSymbol = (TypeSymbol) semanticModel.symbol(queryNode).orElseThrow(); componentMapper.createComponentSchema(components.getSchemas(), typeSymbol); - Schema schema = new Schema(); - schema.set$ref(ConverterCommonUtils.unescapeIdentifier(queryNode.name().text().trim())); + Schema schema = new Schema<>(); + schema.set$ref(unescapeIdentifier(queryNode.name().text().trim())); queryParameter.setSchema(schema); queryParameter.setRequired(true); if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) { queryParameter.setDescription(apidocs.get(queryParamName.trim())); } return queryParameter; + } else if (queryParam.typeName().kind() == SIMPLE_NAME_REFERENCE) { + QueryParameter queryParameter = new QueryParameter(); + Schema refSchema = handleReference(semanticModel, components, (SimpleNameReferenceNode) + queryParam.typeName()); + queryParameter.setSchema(refSchema); + queryParameter.setRequired(true); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + queryParameter.setDescription(apidocs.get(queryParamName)); + } + return queryParameter; } else { QueryParameter queryParameter = createContentTypeForMapJson(queryParamName, false); if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) { @@ -143,7 +156,7 @@ public Parameter createQueryParameter(DefaultableParameterNode defaultableQueryP QueryParameter queryParameter = new QueryParameter(); if (defaultableQueryParam.typeName() instanceof BuiltinSimpleNameReferenceNode && isQuery) { - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema( defaultableQueryParam.typeName().toString().trim()); queryParameter.setSchema(openApiSchema); @@ -160,6 +173,15 @@ public Parameter createQueryParameter(DefaultableParameterNode defaultableQueryP // Handle required array type query parameter ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) defaultableQueryParam.typeName(); queryParameter = handleArrayTypeQueryParameter(queryParamName, arrayNode); + } else if (defaultableQueryParam.typeName().kind() == SIMPLE_NAME_REFERENCE) { + queryParameter.setName(unescapeIdentifier(queryParamName)); + Schema refSchema = handleReference(semanticModel, components, + (SimpleNameReferenceNode) defaultableQueryParam.typeName()); + queryParameter.setSchema(refSchema); + queryParameter.setRequired(true); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + queryParameter.setDescription(apidocs.get(queryParamName)); + } } else { queryParameter = createContentTypeForMapJson(queryParamName, false); if (!apidocs.isEmpty() && defaultableQueryParam.paramName().isPresent() && @@ -198,13 +220,15 @@ public Parameter createQueryParameter(DefaultableParameterNode defaultableQueryP private QueryParameter handleArrayTypeQueryParameter(String queryParamName, ArrayTypeDescriptorNode arrayNode) { QueryParameter queryParameter = new QueryParameter(); ArraySchema arraySchema = new ArraySchema(); - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); TypeDescriptorNode itemTypeNode = arrayNode.memberTypeDesc(); - Schema itemSchema; + Schema itemSchema; if (arrayNode.memberTypeDesc().kind() == OPTIONAL_TYPE_DESC) { itemSchema = ConverterCommonUtils.getOpenApiSchema( ((OptionalTypeDescriptorNode) itemTypeNode).typeDescriptor().toString().trim()); itemSchema.setNullable(true); + } else if (arrayNode.memberTypeDesc().kind() == SIMPLE_NAME_REFERENCE) { + itemSchema = getItemSchemaForReference(arrayNode); } else { itemSchema = ConverterCommonUtils.getOpenApiSchema(itemTypeNode.toString().trim()); } @@ -217,6 +241,11 @@ private QueryParameter handleArrayTypeQueryParameter(String queryParamName, Arra return queryParameter; } + private Schema getItemSchemaForReference(ArrayTypeDescriptorNode arrayNode) { + SimpleNameReferenceNode record = (SimpleNameReferenceNode) arrayNode.memberTypeDesc(); + return handleReference(semanticModel, components, record); + } + /** * Handle optional query parameter. */ @@ -226,17 +255,23 @@ private QueryParameter setOptionalQueryParameter(String queryParamName, Optional if (isOptional.equals(Constants.FALSE)) { queryParameter.setRequired(true); } - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); Node node = typeNode.typeDescriptor(); if (node.kind() == SyntaxKind.ARRAY_TYPE_DESC) { ArraySchema arraySchema = new ArraySchema(); arraySchema.setNullable(true); ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) node; TypeDescriptorNode itemTypeNode = arrayNode.memberTypeDesc(); - Schema itemSchema = ConverterCommonUtils.getOpenApiSchema(itemTypeNode.toString().trim()); + Schema itemSchema; + // handle optional array with references + if (arrayNode.memberTypeDesc().kind() == SIMPLE_NAME_REFERENCE) { + itemSchema = getItemSchemaForReference(arrayNode); + } else { + itemSchema = ConverterCommonUtils.getOpenApiSchema(itemTypeNode.toString().trim()); + } arraySchema.setItems(itemSchema); queryParameter.schema(arraySchema); - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { queryParameter.setDescription(apidocs.get(queryParamName)); } @@ -250,8 +285,18 @@ private QueryParameter setOptionalQueryParameter(String queryParamName, Optional queryParameter.setDescription(apidocs.get(queryParamName)); } return queryParameter; + } else if (node.kind() == SIMPLE_NAME_REFERENCE) { + Schema refSchema = handleReference(semanticModel, components, (SimpleNameReferenceNode) node); + queryParameter.setSchema(refSchema); + if (isOptional.equals(Constants.FALSE)) { + queryParameter.setRequired(true); + } + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + queryParameter.setDescription(apidocs.get(queryParamName)); + } + return queryParameter; } else { - Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(node.toString().trim()); + Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(node.toString().trim()); openApiSchema.setNullable(true); queryParameter.setSchema(openApiSchema); if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { @@ -271,7 +316,7 @@ private QueryParameter createContentTypeForMapJson(String queryParamName, boolea MediaType media = new MediaType(); media.setSchema(objectSchema); queryParameter.setContent(new Content().addMediaType("application/json", media)); - queryParameter.setName(ConverterCommonUtils.unescapeIdentifier(queryParamName)); + queryParameter.setName(unescapeIdentifier(queryParamName)); return queryParameter; } } diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIResponseMapper.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIResponseMapper.java index c9783a747..9fdc895e4 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIResponseMapper.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/service/OpenAPIResponseMapper.java @@ -24,12 +24,14 @@ import io.ballerina.compiler.api.symbols.Documentation; 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.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.AnnotationNode; import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.ExpressionNode; @@ -61,12 +63,15 @@ import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.headers.Header; import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.IntegerSchema; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; +import org.apache.commons.lang3.tuple.ImmutablePair; import java.util.ArrayList; import java.util.HashMap; @@ -89,6 +94,8 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_REFERENCE; import static io.ballerina.openapi.converter.Constants.APPLICATION_PREFIX; import static io.ballerina.openapi.converter.Constants.BODY; +import static io.ballerina.openapi.converter.Constants.BYTE; +import static io.ballerina.openapi.converter.Constants.BYTE_ARRAY; import static io.ballerina.openapi.converter.Constants.CACHE_CONTROL; import static io.ballerina.openapi.converter.Constants.ETAG; import static io.ballerina.openapi.converter.Constants.FALSE; @@ -96,7 +103,11 @@ import static io.ballerina.openapi.converter.Constants.HTTP; import static io.ballerina.openapi.converter.Constants.HTTP_200; import static io.ballerina.openapi.converter.Constants.HTTP_200_DESCRIPTION; +import static io.ballerina.openapi.converter.Constants.HTTP_201; +import static io.ballerina.openapi.converter.Constants.HTTP_201_DESCRIPTION; import static io.ballerina.openapi.converter.Constants.HTTP_204; +import static io.ballerina.openapi.converter.Constants.HTTP_500; +import static io.ballerina.openapi.converter.Constants.HTTP_500_DESCRIPTION; import static io.ballerina.openapi.converter.Constants.HTTP_CODES; import static io.ballerina.openapi.converter.Constants.HTTP_PAYLOAD; import static io.ballerina.openapi.converter.Constants.HTTP_RESPONSE; @@ -110,6 +121,7 @@ import static io.ballerina.openapi.converter.Constants.NO_TRANSFORM; import static io.ballerina.openapi.converter.Constants.OCTECT_STREAM_POSTFIX; import static io.ballerina.openapi.converter.Constants.PLUS; +import static io.ballerina.openapi.converter.Constants.POST; import static io.ballerina.openapi.converter.Constants.PRIVATE; import static io.ballerina.openapi.converter.Constants.PROXY_REVALIDATE; import static io.ballerina.openapi.converter.Constants.PUBLIC; @@ -126,6 +138,7 @@ import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.extractAnnotationFieldDetails; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.extractCustomMediaType; import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.getOpenApiSchema; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; /** * This class uses to map the Ballerina return details to the OAS response. @@ -133,10 +146,12 @@ * @since 2.0.0 */ public class OpenAPIResponseMapper { + private final SemanticModel semanticModel; private final Components components; private final List errors = new ArrayList<>(); private final Location location; + private String httpMethod; public List getErrors() { return errors; @@ -151,11 +166,12 @@ public OpenAPIResponseMapper(SemanticModel semanticModel, Components components, /** * This function for mapping the function return type details with OAS response schema. * - * @param resource FunctionDefinitionNode for relevant resource function. - * @param operationAdaptor OperationAdaptor model for holding operation details specific to HTTP operation. + * @param resource FunctionDefinitionNode for relevant resource function. + * @param operationAdaptor OperationAdaptor model for holding operation details specific to HTTP operation. */ public void getResourceOutput(FunctionDefinitionNode resource, OperationAdaptor operationAdaptor) { + httpMethod = operationAdaptor.getHttpOperation().toUpperCase(Locale.ENGLISH); FunctionSignatureNode functionSignature = resource.functionSignature(); Optional returnTypeDescriptor = functionSignature.returnTypeDesc(); io.swagger.v3.oas.models.Operation operation = operationAdaptor.getOperation(); @@ -169,13 +185,14 @@ public void getResourceOutput(FunctionDefinitionNode resource, OperationAdaptor Map headers = new LinkedHashMap<>(); if (!annotations.isEmpty()) { for (AnnotationNode annotation : annotations) { - apiResponses.putAll(extractReturnAnnotationDetails(operationAdaptor, customMediaType, - returnType, headers, annotation)); + ApiResponses responses = extractReturnAnnotationDetails(operationAdaptor, customMediaType, + returnType, headers, annotation); + addResponse(apiResponses, Optional.of(responses)); } } else { - Optional responses = getAPIResponses(operationAdaptor, apiResponses, returnType, + Optional responses = getAPIResponses(operationAdaptor, returnType, customMediaType, headers); - responses.ifPresent(apiResponses::putAll); + addResponse(apiResponses, responses); } } else { // When the return type is not mention in the resource function. @@ -189,11 +206,11 @@ public void getResourceOutput(FunctionDefinitionNode resource, OperationAdaptor /** * Extract annotation details for generate headers. * - * @param operationAdaptor - Operation model - * @param customMediaType - Prefix media type for response - * @param typeNode - Return node - * @param headers - OAS header - * @param annotation - Annotation node + * @param operationAdaptor - Operation model + * @param customMediaType - Prefix media type for response + * @param typeNode - Return node + * @param headers - OAS header + * @param annotation - Annotation node */ private ApiResponses extractReturnAnnotationDetails(OperationAdaptor operationAdaptor, Optional customMediaType, Node typeNode, @@ -203,24 +220,19 @@ private ApiResponses extractReturnAnnotationDetails(OperationAdaptor operationAd if (annotation.annotReference().toString().trim().equals("http:Cache")) { CacheConfigAnnotation cacheConfigAnn = new CacheConfigAnnotation(); annotation.annotValue().ifPresentOrElse( - (value) -> { - updateResponseHeaderWithCacheValues(headers, setCacheConfigValues(value.fields())); - }, - ()-> { - updateResponseHeaderWithCacheValues(headers, cacheConfigAnn); - } - ); + value -> updateResponseHeaderWithCacheValues(headers, setCacheConfigValues(value.fields())), + () -> updateResponseHeaderWithCacheValues(headers, cacheConfigAnn)); } else if (annotation.annotReference().toString().trim().equals(HTTP_PAYLOAD)) { overrideMediaType = extractAnnotationFieldDetails(HTTP_PAYLOAD, MEDIA_TYPE, annotation, semanticModel); } - Optional responses = getAPIResponses(operationAdaptor, apiResponses, typeNode, + Optional responses = getAPIResponses(operationAdaptor, typeNode, customMediaType, headers); // Override the mediaType with given type if (responses.isPresent() && !overrideMediaType.isEmpty()) { ApiResponses updatedResponse = overrideMediaType(customMediaType, overrideMediaType, responses.get()); - apiResponses.putAll(updatedResponse); + addResponse(apiResponses, Optional.of(updatedResponse)); } else { - responses.ifPresent(apiResponses::putAll); + addResponse(apiResponses, responses); } return apiResponses; } @@ -228,14 +240,15 @@ private ApiResponses extractReturnAnnotationDetails(OperationAdaptor operationAd /** * This util function is used to override the MediaType with given mediaType inside the payload annotation. * ex:

-     *     @http:Payload {mediaType: ["application/json", "application/xml"]}
+     *     http:Payload {mediaType: ["application/json", "application/xml"]}
      * 
- * @param customMediaType This customMediaType comes from service configure annotation. - * @param overrideMediaType MediaTypes inside payload annotation. - * @param responses Generated response. + * + * @param customMediaType This customMediaType comes from service configure annotation. + * @param overrideMediaType MediaTypes inside payload annotation. + * @param responses Generated response. */ private ApiResponses overrideMediaType(Optional customMediaType, List overrideMediaType, - ApiResponses responses) { + ApiResponses responses) { ApiResponses updatedResponse = new ApiResponses(); for (Map.Entry next : responses.entrySet()) { ApiResponse response = next.getValue(); @@ -254,10 +267,10 @@ private ApiResponses overrideMediaType(Optional customMediaType, List customMediaType, List fields) { CacheConfigAnnotation cacheConfig = new CacheConfigAnnotation(); // when field values has -- create a function for have the default values. Spliterator spliterator = fields.spliterator(); - spliterator.forEachRemaining(field-> { + spliterator.forEachRemaining(field -> { if (field.kind() == SyntaxKind.SPECIFIC_FIELD) { SpecificFieldNode specificFieldNode = (SpecificFieldNode) field; // generate string @@ -412,60 +425,64 @@ private void setCacheConfigField(CacheConfigAnnotation cacheConfig, String field * * @return {@link io.swagger.v3.oas.models.responses.ApiResponses} for operation. */ - private Optional getAPIResponses(OperationAdaptor operationAdaptor, ApiResponses apiResponses, + private Optional getAPIResponses(OperationAdaptor operationAdaptor, Node typeNode, Optional customMediaPrefix, Map headers) { ApiResponse apiResponse = new ApiResponse(); + ApiResponses apiResponses = new ApiResponses(); io.swagger.v3.oas.models.media.MediaType mediaType = new io.swagger.v3.oas.models.media.MediaType(); + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; + String mediaTypeString; switch (typeNode.kind()) { case QUALIFIED_NAME_REFERENCE: QualifiedNameReferenceNode qNode = (QualifiedNameReferenceNode) typeNode; - return handleQualifiedNameType(apiResponses, customMediaPrefix, headers, apiResponse, qNode); + return handleQualifiedNameType(apiResponses, customMediaPrefix, headers, apiResponse, qNode); case FLOAT_TYPE_DESC: case DECIMAL_TYPE_DESC: case INT_TYPE_DESC: case STRING_TYPE_DESC: case BOOLEAN_TYPE_DESC: - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); - String type = typeNode.toString().toLowerCase(Locale.ENGLISH).trim(); - Schema schema = ConverterCommonUtils.getOpenApiSchema(type); + apiResponse = setCacheHeader(headers, apiResponse, statusCode); + String type = typeNode.toString().toLowerCase(Locale.ENGLISH).trim(); + Schema schema = ConverterCommonUtils.getOpenApiSchema(type); Optional media = convertBallerinaMIMEToOASMIMETypes(type, customMediaPrefix); if (media.isPresent()) { mediaType.setSchema(schema); - apiResponse.description(HTTP_200_DESCRIPTION); + apiResponse.description(description); apiResponse.content(new Content().addMediaType(media.get(), mediaType)); - apiResponses.put(HTTP_200, apiResponse); + apiResponses.put(statusCode, apiResponse); return Optional.of(apiResponses); } else { return Optional.empty(); } case JSON_TYPE_DESC: - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); + setCacheHeader(headers, apiResponse, statusCode); mediaType.setSchema(new ObjectSchema()); - mediaTypeString = customMediaPrefix.isPresent() ? APPLICATION_PREFIX + customMediaPrefix.get() + - JSON_POSTFIX : MediaType.APPLICATION_JSON; + mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + JSON_POSTFIX) + .orElse(APPLICATION_JSON); apiResponse.content(new Content().addMediaType(mediaTypeString, mediaType)); - apiResponse.description(HTTP_200_DESCRIPTION); - apiResponses.put(HTTP_200, apiResponse); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); return Optional.of(apiResponses); case XML_TYPE_DESC: - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); + setCacheHeader(headers, apiResponse, statusCode); mediaType.setSchema(new ObjectSchema()); - mediaTypeString = customMediaPrefix.isPresent() ? APPLICATION_PREFIX + customMediaPrefix.get() + - XML_POSTFIX : MediaType.APPLICATION_XML; + mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + XML_POSTFIX) + .orElse(MediaType.APPLICATION_XML); apiResponse.content(new Content().addMediaType(mediaTypeString, mediaType)); - apiResponse.description(HTTP_200_DESCRIPTION); - apiResponses.put(HTTP_200, apiResponse); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); return Optional.of(apiResponses); case SIMPLE_NAME_REFERENCE: - SimpleNameReferenceNode recordNode = (SimpleNameReferenceNode) typeNode; + SimpleNameReferenceNode recordNode = (SimpleNameReferenceNode) typeNode; Map schemas = components.getSchemas(); handleReferenceResponse(operationAdaptor, recordNode, schemas, apiResponses, customMediaPrefix, headers); return Optional.of(apiResponses); case UNION_TYPE_DESC: - return mapUnionReturns(operationAdaptor, apiResponses, + return mapUnionReturns(operationAdaptor, (UnionTypeDescriptorNode) typeNode, customMediaPrefix, headers); case RECORD_TYPE_DESC: return mapInlineRecordInReturn(operationAdaptor, apiResponses, @@ -475,26 +492,40 @@ private Optional getAPIResponses(OperationAdaptor operationAdaptor (ArrayTypeDescriptorNode) typeNode, apiResponse, mediaType, customMediaPrefix, headers); case ERROR_TYPE_DESC: // Return type is given as error or error? in the ballerina it will generate 500 response. - apiResponse.description("Found unexpected output"); - mediaType.setSchema(new StringSchema()); - apiResponse.content(new Content().addMediaType(MediaType.TEXT_PLAIN, mediaType)); - apiResponses.put("500", apiResponse); + apiResponse.description(HTTP_500_DESCRIPTION); + ObjectSchema errorSchema = new ObjectSchema(); + // Create ErrorPayload object properties. + Map properties = new HashMap<>(); + properties.put("timestamp", new StringSchema().description("Timestamp of the error")); + properties.put("status", new IntegerSchema().description("Relevant HTTP status code")); + properties.put("reason", new StringSchema().description("Reason phrase")); + properties.put("message", new StringSchema().description("Error message")); + properties.put("path", new StringSchema().description("Request path")); + properties.put("method", new StringSchema().description("Method type of the request")); + errorSchema.setProperties(properties); + if (components.getSchemas() == null) { + components.setSchemas(new HashMap<>()); + } + components.getSchemas().put("ErrorPayload", errorSchema); + mediaType.setSchema(new Schema<>().$ref("ErrorPayload")); + apiResponse.content(new Content().addMediaType(APPLICATION_JSON, mediaType)); + apiResponses.put(HTTP_500, apiResponse); return Optional.of(apiResponses); case OPTIONAL_TYPE_DESC: - return getAPIResponses(operationAdaptor, apiResponses, + return getAPIResponses(operationAdaptor, ((OptionalTypeDescriptorNode) typeNode).typeDescriptor(), customMediaPrefix, headers); case MAP_TYPE_DESC: - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); + setCacheHeader(headers, apiResponse, statusCode); MapTypeDescriptorNode mapNode = (MapTypeDescriptorNode) typeNode; ObjectSchema objectSchema = new ObjectSchema(); Schema apiSchema = getOpenApiSchema(mapNode.mapTypeParamsNode().typeNode().kind()); objectSchema.additionalProperties(apiSchema); mediaType.setSchema(objectSchema); - mediaTypeString = customMediaPrefix.isPresent() ? APPLICATION_PREFIX + customMediaPrefix.get() + - JSON_POSTFIX : MediaType.APPLICATION_JSON; + mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + JSON_POSTFIX) + .orElse(APPLICATION_JSON); apiResponse.content(new Content().addMediaType(mediaTypeString, mediaType)); - apiResponse.description(HTTP_200_DESCRIPTION); - apiResponses.put(HTTP_200, apiResponse); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); return Optional.of(apiResponses); default: DiagnosticMessages errorMessage = DiagnosticMessages.OAS_CONVERTOR_101; @@ -529,7 +560,7 @@ private Optional handleQualifiedNameType(ApiResponses apiResponses Optional code = generateApiResponseCode(qNode.identifier().toString().trim()); if (code.isPresent()) { apiResponse.description(qNode.identifier().toString().trim()); - apiResponse = setCacheHeader(headers, apiResponse, code.get()); + setCacheHeader(headers, apiResponse, code.get()); apiResponses.put(code.get(), apiResponse); return Optional.of(apiResponses); } else { @@ -538,9 +569,19 @@ private Optional handleQualifiedNameType(ApiResponses apiResponses } } else { Symbol symbol = semanticModel.symbol(qNode).get(); - if (symbol instanceof TypeReferenceTypeSymbol) { + if (symbol instanceof TypeReferenceTypeSymbol) { TypeReferenceTypeSymbol typeRef = (TypeReferenceTypeSymbol) symbol; TypeSymbol typeSymbol = typeRef.typeDescriptor(); + if (typeSymbol.typeKind() == TypeDescKind.INTERSECTION) { + List memberTypes = ((IntersectionTypeSymbol) typeSymbol).memberTypeDescriptors(); + for (TypeSymbol memberType : memberTypes) { + if (!(memberType instanceof ReadonlyTypeSymbol)) { + //TODO : address the rest of the simple name reference types + typeSymbol = memberType; + break; + } + } + } if (typeSymbol.typeKind() == TypeDescKind.RECORD) { ApiResponses responses = handleRecordTypeSymbol(qNode.identifier().text().trim(), components.getSchemas(), customMediaPrefix, typeRef, @@ -563,10 +604,13 @@ private Optional getApiResponsesForArrayTypes(OperationAdaptor ope io.swagger.v3.oas.models.media.MediaType mediaType, Optional customMediaPrefix, Map headers) { - Map schemas02 = components.getSchemas(); + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; + + Map schemas = components.getSchemas(); if (array.memberTypeDesc().kind() == SIMPLE_NAME_REFERENCE) { handleReferenceResponse(operationAdaptor, (SimpleNameReferenceNode) array.memberTypeDesc(), - schemas02, apiResponses, customMediaPrefix, headers); + schemas, apiResponses, customMediaPrefix, headers); } else if (array.memberTypeDesc().kind() == QUALIFIED_NAME_REFERENCE) { Optional optionalAPIResponses = handleQualifiedNameType(new ApiResponses(), customMediaPrefix, headers, apiResponse, @@ -578,18 +622,23 @@ private Optional getApiResponsesForArrayTypes(OperationAdaptor ope } } else { ArraySchema arraySchema = new ArraySchema(); - String type02 = array.memberTypeDesc().kind().toString().trim().split("_")[0]. + String type = array.memberTypeDesc().kind().toString().trim().split("_")[0]. toLowerCase(Locale.ENGLISH); - Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(type02); - Optional mimeType = convertBallerinaMIMEToOASMIMETypes(type02, customMediaPrefix); + type = type.equals(BYTE) ? BYTE_ARRAY : type; + Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(type); + Optional mimeType = convertBallerinaMIMEToOASMIMETypes(type, customMediaPrefix); if (mimeType.isEmpty()) { return Optional.empty(); } - arraySchema.setItems(openApiSchema); - mediaType.setSchema(arraySchema); - apiResponse.description(HTTP_200_DESCRIPTION); + if (type.equals(BYTE_ARRAY)) { + mediaType.setSchema(openApiSchema); + } else { + arraySchema.setItems(openApiSchema); + mediaType.setSchema(arraySchema); + } + apiResponse.description(description); apiResponse.content(new Content().addMediaType(mimeType.get(), mediaType)); - apiResponses.put(HTTP_200, apiResponse); + apiResponses.put(statusCode, apiResponse); } return Optional.of(apiResponses); } @@ -627,14 +676,15 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio io.swagger.v3.oas.models.media.MediaType mediaType, Optional customMediaPrefix, Map headers) { + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; NodeList fields = typeNode.fields(); - Optional httpCode = Optional.of(HTTP_200); - Schema inlineSchema = new Schema(); - String description = HTTP_200_DESCRIPTION; - Optional mediaTypeResponse = Optional.of(MediaType.APPLICATION_JSON); + Optional httpCode = Optional.of(statusCode); + Schema inlineSchema = new Schema<>(); + Optional mediaTypeResponse = Optional.of(APPLICATION_JSON); boolean ishttpTypeInclusion = false; - Map properties = new HashMap<>(); + Map properties = new HashMap<>(); if (fields.stream().anyMatch(module -> module.kind() == TYPE_REFERENCE)) { ishttpTypeInclusion = true; } @@ -643,7 +693,7 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio // 3- scenarios returns record {| int id; string body;|} - done // 4- scenarios returns record {| int id; Person body;|} - done - for (Node field: fields) { + for (Node field : fields) { // TODO Handle http typeInclusion, check it comes from http module if (field.kind() == TYPE_REFERENCE) { TypeReferenceNode typeFieldNode = (TypeReferenceNode) field; @@ -659,10 +709,10 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio Node type01 = recordField.typeName(); if (recordField.typeName().kind() == SIMPLE_NAME_REFERENCE) { Map componentsSchemas = components.getSchemas(); - SimpleNameReferenceNode nameRefNode = (SimpleNameReferenceNode) type01; + SimpleNameReferenceNode nameRefNode = (SimpleNameReferenceNode) type01; handleReferenceResponse(operationAdaptor, nameRefNode, componentsSchemas, apiResponses, customMediaPrefix, headers); - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref(ConverterCommonUtils.unescapeIdentifier( recordField.typeName().toString().trim())); properties.put(recordField.fieldName().text(), referenceSchema); @@ -670,7 +720,7 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio //TODO array fields handling mediaTypeResponse = convertBallerinaMIMEToOASMIMETypes(recordField.typeName().toString().trim(), customMediaPrefix); - Schema propertySchema = ConverterCommonUtils.getOpenApiSchema( + Schema propertySchema = ConverterCommonUtils.getOpenApiSchema( recordField.typeName().toString().trim()); properties.put(recordField.fieldName().text(), propertySchema); } @@ -679,7 +729,7 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio if (!ishttpTypeInclusion) { inlineSchema = new ObjectSchema(); inlineSchema.setProperties(properties); - mediaTypeResponse = Optional.of(MediaType.APPLICATION_JSON); + mediaTypeResponse = Optional.of(APPLICATION_JSON); if (customMediaPrefix.isPresent()) { mediaTypeResponse = Optional.of(APPLICATION_PREFIX + customMediaPrefix.get() + JSON_POSTFIX); } @@ -688,7 +738,7 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio apiResponse.description(description); if (mediaTypeResponse.isPresent() && httpCode.isPresent()) { apiResponse.content(new Content().addMediaType(mediaTypeResponse.get(), mediaType)); - apiResponse = setCacheHeader(headers, apiResponse, httpCode.get()); + setCacheHeader(headers, apiResponse, httpCode.get()); apiResponses.put(httpCode.get(), apiResponse); return Optional.of(apiResponses); } else { @@ -707,48 +757,85 @@ private Optional mapInlineRecordInReturn(OperationAdaptor operatio * } * */ - private Optional mapUnionReturns(OperationAdaptor operationAdaptor, ApiResponses apiResponses, + private Optional mapUnionReturns(OperationAdaptor operationAdaptor, UnionTypeDescriptorNode typeNode, Optional customMediaPrefix , Map headers) { TypeDescriptorNode rightNode = typeNode.rightTypeDesc(); TypeDescriptorNode leftNode = typeNode.leftTypeDesc(); + ApiResponses apiResponses = new ApiResponses(); // Handle leftNode because it is main node - Optional apiResponse = getAPIResponses(operationAdaptor, apiResponses, leftNode, + Optional apiResponse = getAPIResponses(operationAdaptor, leftNode, customMediaPrefix, headers); - apiResponse.ifPresent(apiResponses::putAll); + addResponse(apiResponses, apiResponse); // 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(); - Optional apiResponsesLeft = getAPIResponses(operationAdaptor, apiResponses, leftNode, + Optional apiResponsesLeft = getAPIResponses(operationAdaptor, leftNode, customMediaPrefix, headers); - apiResponsesLeft.ifPresent(apiResponses::putAll); + addResponse(apiResponses, apiResponsesLeft); } } } else { - Optional apiResponsesRight = getAPIResponses(operationAdaptor, apiResponses, rightNode, + Optional apiResponsesRight = getAPIResponses(operationAdaptor, rightNode, customMediaPrefix, headers); - apiResponsesRight.ifPresent(apiResponses::putAll); + addResponse(apiResponses, apiResponsesRight); } return Optional.of(apiResponses); } + private static void addResponse(ApiResponses apiResponses, Optional apiResponse) { + apiResponse.ifPresent(responses -> responses.forEach((key, value) -> { + if (apiResponses.containsKey(key)) { + ApiResponse res = apiResponses.get(key); + Content content = res.getContent(); + if (content == null) { + content = new Content(); + } + if (value.getContent() != null) { + String mediaType = value.getContent().keySet().iterator().next(); + Schema newSchema = value.getContent().values().iterator().next().getSchema(); + if (content.containsKey(mediaType)) { + Schema schema = content.get(mediaType).getSchema(); + if (schema instanceof ComposedSchema && ((ComposedSchema) schema).getOneOf() != null) { + schema.getOneOf().add(newSchema); + content.put(mediaType, new io.swagger.v3.oas.models.media.MediaType().schema(schema)); + } else { + ComposedSchema composedSchema = new ComposedSchema(); + composedSchema.addOneOfItem(schema); + composedSchema.addOneOfItem(newSchema); + io.swagger.v3.oas.models.media.MediaType updatedMediaContent = + new io.swagger.v3.oas.models.media.MediaType().schema(composedSchema); + content.put(mediaType, updatedMediaContent); + } + } else { + content.put(mediaType, value.getContent().values().iterator().next()); + } + } + res.content(content); + apiResponses.put(key, res); + } else { + apiResponses.put(key, value); + } + })); + } + /** * Convert ballerina MIME types to OAS MIME types. */ private Optional convertBallerinaMIMEToOASMIMETypes(String type, Optional customMediaPrefix) { switch (type) { - case MediaType.APPLICATION_JSON: + case APPLICATION_JSON: case Constants.JSON: case Constants.INT: case Constants.FLOAT: case Constants.DECIMAL: case Constants.BOOLEAN: return Optional.of(customMediaPrefix.map(s -> APPLICATION_PREFIX + s + JSON_POSTFIX) - .orElse(MediaType.APPLICATION_JSON)); + .orElse(APPLICATION_JSON)); case MediaType.APPLICATION_XML: case Constants.XML: return Optional.of(customMediaPrefix.map(s -> APPLICATION_PREFIX + s + XML_POSTFIX). @@ -792,7 +879,6 @@ private void handleReferenceResponse(OperationAdaptor operationAdaptor, SimpleNa Map schema, ApiResponses apiResponses, Optional customMediaPrefix, Map headers) { ApiResponse apiResponse = new ApiResponse(); - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); Optional symbol = semanticModel.symbol(referenceNode); TypeSymbol typeSymbol = (TypeSymbol) symbol.orElseThrow(); //handle record for components @@ -800,30 +886,84 @@ private void handleReferenceResponse(OperationAdaptor operationAdaptor, SimpleNa String mediaTypeString; // Check typeInclusion is related to the http status code if (referenceNode.parent().kind().equals(ARRAY_TYPE_DESC)) { + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; + setCacheHeader(headers, apiResponse, statusCode); io.swagger.v3.oas.models.media.MediaType media = new io.swagger.v3.oas.models.media.MediaType(); ArraySchema arraySchema = new ArraySchema(); componentMapper.createComponentSchema(schema, typeSymbol); errors.addAll(componentMapper.getDiagnostics()); - arraySchema.setItems(new Schema().$ref(ConverterCommonUtils.unescapeIdentifier( + arraySchema.setItems(new Schema<>().$ref(ConverterCommonUtils.unescapeIdentifier( referenceNode.name().toString().trim()))); media.setSchema(arraySchema); - apiResponse.description(HTTP_200_DESCRIPTION); + apiResponse.description(description); mediaTypeString = customMediaPrefix.isPresent() ? APPLICATION_PREFIX + customMediaPrefix + JSON_POSTFIX : - MediaType.APPLICATION_JSON; + APPLICATION_JSON; apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - apiResponses.put(HTTP_200, apiResponse); + apiResponses.put(statusCode, apiResponse); } else if (typeSymbol.typeKind() == TypeDescKind.TYPE_REFERENCE) { TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) typeSymbol; + TypeSymbol referredTypeSymbol = typeReferenceTypeSymbol.typeDescriptor(); + if (referredTypeSymbol.typeKind() == TypeDescKind.INTERSECTION) { + referredTypeSymbol = componentMapper.excludeReadonlyIfPresent(referredTypeSymbol); + } String referenceName = referenceNode.name().toString().trim(); - ApiResponses responses = handleRecordTypeSymbol(referenceName, schema, customMediaPrefix, - typeReferenceTypeSymbol, componentMapper, headers); - apiResponses.putAll(responses); + String referredTypeName = referredTypeSymbol.getName().isPresent() ? + referredTypeSymbol.getName().get() : ""; + + if (referredTypeSymbol.typeKind() == TypeDescKind.RECORD) { + ApiResponses responses = handleRecordTypeSymbol(referenceName, schema, customMediaPrefix, + typeReferenceTypeSymbol, componentMapper, headers); + apiResponses.putAll(responses); + } else if (referredTypeSymbol.typeKind() == TypeDescKind.ERROR) { + io.swagger.v3.oas.models.media.MediaType mediaType = new io.swagger.v3.oas.models.media.MediaType(); + apiResponse.description(HTTP_500_DESCRIPTION); + mediaType.setSchema(new StringSchema()); + apiResponse.content(new Content().addMediaType(MediaType.TEXT_PLAIN, mediaType)); + apiResponses.put(HTTP_500, apiResponse); + } else if (referredTypeSymbol.typeKind() == TypeDescKind.TYPE_REFERENCE && + generateApiResponseCode(referredTypeName).isPresent()) { + Optional code = generateApiResponseCode(referredTypeName); + apiResponse.description(referredTypeName); + setCacheHeader(headers, apiResponse, code.get()); + apiResponses.put(code.get(), apiResponse); + } else { + ApiResponses responses = createResponseForTypeReferenceTypeReturns(referenceName, + typeReferenceTypeSymbol, schema, customMediaPrefix, + componentMapper, headers); + apiResponses.putAll(responses); + } } //Check content and status code if it is in 200 range then add the header operationAdaptor.getOperation().setResponses(apiResponses); } + /** + * Create responses when http errors are present in the union type. + * + * @param unionTypeSymbol union type symbol + * @param headers headers + * @return api responses + */ + public Optional createResponsesForErrorsInUnion(UnionTypeSymbol unionTypeSymbol, + Map headers) { + ApiResponses apiResponses = new ApiResponses(); + + for (TypeSymbol memberTypeDescriptor : unionTypeSymbol.memberTypeDescriptors()) { + memberTypeDescriptor.getName().ifPresent(name -> { + if (HTTP_CODES.containsKey(name)) { + ApiResponse apiResponse = new ApiResponse(); + Optional code = generateApiResponseCode(name); + apiResponse.description(name); + setCacheHeader(headers, apiResponse, code.get()); + apiResponses.put(code.get(), apiResponse); + } + }); + } + return apiResponses.isEmpty() ? Optional.empty() : Optional.of(apiResponses); + } + private ApiResponses handleRecordTypeSymbol(String referenceName, Map schema, Optional customMediaPrefix, TypeReferenceTypeSymbol typeSymbol, OpenAPIComponentMapper componentMapper, @@ -862,25 +1002,123 @@ private ApiResponses handleRecordTypeSymbol(String referenceName, Map schema, + Optional customMediaPrefix, + + OpenAPIComponentMapper componentMapper, + Map headers) { + + TypeSymbol referredTypeSymbol = typeReferenceTypeSymbol.typeDescriptor(); + TypeDescKind typeDescKind = referredTypeSymbol.typeKind(); + io.swagger.v3.oas.models.media.MediaType media = new io.swagger.v3.oas.models.media.MediaType(); + + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; + + ApiResponses apiResponses = new ApiResponses(); + if (referredTypeSymbol.typeKind() == TypeDescKind.INTERSECTION) { + referredTypeSymbol = componentMapper.excludeReadonlyIfPresent(referredTypeSymbol); + typeDescKind = referredTypeSymbol.typeKind(); + } + + if (typeDescKind == TypeDescKind.UNION) { + UnionTypeSymbol unionTypeSymbol = (UnionTypeSymbol) referredTypeSymbol; + createResponsesForErrorsInUnion(unionTypeSymbol, headers).ifPresent(apiResponses::putAll); + } + + componentMapper.createComponentSchema(schema, typeReferenceTypeSymbol); + errors.addAll(componentMapper.getDiagnostics()); + media.setSchema(new Schema<>().$ref(ConverterCommonUtils.unescapeIdentifier(referenceName))); + + ImmutablePair mediaTypePair = getMediaTypeForTypeReferenceTypeReturns(referredTypeSymbol, + typeDescKind, customMediaPrefix); + + String mediaTypeString = mediaTypePair.getLeft(); + if (customMediaPrefix.isPresent()) { + mediaTypeString = APPLICATION_PREFIX + customMediaPrefix.get() + mediaTypePair.getRight(); + } + + ApiResponse apiResponse = new ApiResponse(); + setCacheHeader(headers, apiResponse, statusCode); + apiResponse.content(new Content().addMediaType(mediaTypeString, media)); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); + + return apiResponses; + } + + + private static ImmutablePair getMediaTypeForTypeReferenceTypeReturns(TypeSymbol referredTypeSymbol, + TypeDescKind typeDescKind, + Optional + customMediaPrefix) { + ImmutablePair mediaType = null; + switch (typeDescKind) { + case XML: + mediaType = new ImmutablePair<>(MediaType.APPLICATION_XML, XML_POSTFIX); + break; + case STRING: + mediaType = new ImmutablePair<>(MediaType.TEXT_PLAIN, TEXT_POSTFIX); + break; + case BYTE: + mediaType = new ImmutablePair<>(MediaType.APPLICATION_OCTET_STREAM, OCTECT_STREAM_POSTFIX); + break; + case ARRAY: + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol) referredTypeSymbol; + TypeSymbol memberTypeDesc = arrayTypeSymbol.memberTypeDescriptor(); + mediaType = getMediaTypeForTypeReferenceTypeReturns(memberTypeDesc, memberTypeDesc.typeKind(), + customMediaPrefix); + break; + case UNION: + UnionTypeSymbol unionTypeSymbol = (UnionTypeSymbol) referredTypeSymbol; + boolean isNil = unionTypeSymbol.memberTypeDescriptors().stream().anyMatch( + memberTypeDescriptor -> memberTypeDescriptor.typeKind() == TypeDescKind.NIL); + if (unionTypeSymbol.memberTypeDescriptors().size() == 2 && isNil) { + for (TypeSymbol memberTypeDescriptor : unionTypeSymbol.memberTypeDescriptors()) { + if (memberTypeDescriptor.typeKind() != TypeDescKind.NIL) { + mediaType = getMediaTypeForTypeReferenceTypeReturns(memberTypeDescriptor, + memberTypeDescriptor.typeKind(), customMediaPrefix); + break; + } + } + } else { + mediaType = new ImmutablePair<>(MediaType.APPLICATION_JSON, JSON_POSTFIX); + } + break; + default: + mediaType = new ImmutablePair<>(MediaType.APPLICATION_JSON, JSON_POSTFIX); + break; + } + + return mediaType; + } + private ApiResponses createResponseForRecord(String referenceName, Map schema, Optional customMediaPrefix, TypeSymbol typeSymbol, OpenAPIComponentMapper componentMapper, io.swagger.v3.oas.models.media.MediaType media, Map headers) { + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; ApiResponses apiResponses = new ApiResponses(); String mediaTypeString; componentMapper.createComponentSchema(schema, typeSymbol); errors.addAll(componentMapper.getDiagnostics()); - media.setSchema(new Schema().$ref(ConverterCommonUtils.unescapeIdentifier(referenceName))); - mediaTypeString = MediaType.APPLICATION_JSON; + media.setSchema(new Schema<>().$ref(ConverterCommonUtils.unescapeIdentifier(referenceName))); + mediaTypeString = APPLICATION_JSON; if (customMediaPrefix.isPresent()) { mediaTypeString = APPLICATION_PREFIX + customMediaPrefix.get() + JSON_POSTFIX; } ApiResponse apiResponse = new ApiResponse(); - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); + setCacheHeader(headers, apiResponse, statusCode); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - apiResponse.description(HTTP_200_DESCRIPTION); - apiResponses.put(HTTP_200, apiResponse); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); return apiResponses; } @@ -907,7 +1145,7 @@ private Optional handleRecordHasHttpTypeInclusionField(Map handleRecordHasHttpTypeInclusionField(Map().$ref(ConverterCommonUtils.unescapeIdentifier( body.typeDescriptor().getName().orElseThrow().trim()))); mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + JSON_POSTFIX) - .orElse(MediaType.APPLICATION_JSON); + .orElse(APPLICATION_JSON); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - } else if (body.typeDescriptor().typeKind() == TypeDescKind.STRING) { + } else if (typeDescKind == TypeDescKind.STRING) { media.setSchema(new StringSchema()); mediaTypeString = customMediaPrefix.map(s -> TEXT_PREFIX + s + TEXT_POSTFIX).orElse(MediaType.TEXT_PLAIN); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - } else if (body.typeDescriptor().typeKind() == TypeDescKind.XML) { + } else if (typeDescKind == TypeDescKind.XML) { media.setSchema(new ObjectSchema()); mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + XML_POSTFIX) .orElse(MediaType.APPLICATION_XML); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - } else if (body.typeDescriptor().typeKind() == TypeDescKind.MAP && + } else if (typeDescKind == TypeDescKind.MAP && (((MapTypeSymbol) body.typeDescriptor()).typeParam().typeKind() == TypeDescKind.STRING)) { mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + X_WWW_FORM_URLENCODED_POSTFIX) .orElse(MediaType.APPLICATION_FORM_URLENCODED); - Schema objectSchema = new ObjectSchema(); + Schema objectSchema = new ObjectSchema(); objectSchema.additionalProperties(new StringSchema()); media.setSchema(objectSchema); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); + } else if (typeDescKind == TypeDescKind.UNION) { + UnionTypeSymbol unionType = (UnionTypeSymbol) body.typeDescriptor(); + List typeSymbols = unionType.memberTypeDescriptors(); + //store media type based on the members of the union type + Map contentDetails = new LinkedHashMap<>(); + for (TypeSymbol type : typeSymbols) { + ImmutablePair mediaTypes = + getMediaTypeForTypeReferenceTypeReturns(type, type.typeKind(), customMediaPrefix); + mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + mediaTypes.getRight()) + .orElseGet(mediaTypes::getLeft); + Schema mediaSchema = getOpenApiSchema(type.typeKind().getName()); + if (type.typeKind() == TypeDescKind.TYPE_REFERENCE) { + componentMapper.createComponentSchema(schema, type); + errors.addAll(componentMapper.getDiagnostics()); + String recordName = type.getName().orElseThrow().trim(); + mediaSchema.set$ref(ConverterCommonUtils.unescapeIdentifier(recordName)); + } + if (contentDetails.containsKey(mediaTypeString)) { + Schema oldSchema = contentDetails.get(mediaTypeString); + if (oldSchema instanceof ComposedSchema && oldSchema.getOneOf() != null) { + oldSchema.getOneOf().add(mediaSchema); + contentDetails.put(mediaTypeString, oldSchema); + } else { + ComposedSchema composedSchema = new ComposedSchema(); + composedSchema.addOneOfItem(oldSchema); + composedSchema.addOneOfItem(mediaSchema); + contentDetails.put(mediaTypeString, composedSchema); + } + } else { + contentDetails.put(mediaTypeString, mediaSchema); + } + } + Content content = new Content(); + for (Map.Entry entry : contentDetails.entrySet()) { + io.swagger.v3.oas.models.media.MediaType mediaType = + new io.swagger.v3.oas.models.media.MediaType(); + + mediaTypeString = entry.getKey(); + mediaType.setSchema(entry.getValue()); + content.addMediaType(mediaTypeString, mediaType); + } + apiResponse.content(content); } apiResponse.description(typeInSymbol.getName().orElseThrow().trim()); apiResponses.put(code.get(), apiResponse); @@ -954,15 +1235,18 @@ private Optional handleRecordHasHttpTypeInclusionField(Map().$ref(ConverterCommonUtils.unescapeIdentifier(typeSymbol.getName().get()))); + mediaTypeString = APPLICATION_JSON; if (customMediaPrefix.isPresent()) { mediaTypeString = APPLICATION_PREFIX + customMediaPrefix.get() + JSON_POSTFIX; } - apiResponse = setCacheHeader(headers, apiResponse, HTTP_200); + String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200; + String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION; + + setCacheHeader(headers, apiResponse, statusCode); apiResponse.content(new Content().addMediaType(mediaTypeString, media)); - apiResponse.description(HTTP_200_DESCRIPTION); - apiResponses.put(HTTP_200, apiResponse); + apiResponse.description(description); + apiResponses.put(statusCode, apiResponse); } return Optional.of(apiResponses); } @@ -970,8 +1254,8 @@ private Optional handleRecordHasHttpTypeInclusionField(Map headers, RecordFieldSymbol header) { @@ -980,11 +1264,11 @@ private void extractResponseHeaders(Map headers, RecordFieldSymb if (headerType.typeDescriptor() instanceof RecordTypeSymbol) { RecordTypeSymbol recordTypeSymbol = (RecordTypeSymbol) headerType.typeDescriptor(); Map rfields = recordTypeSymbol.fieldDescriptors(); - for (Map.Entry field: rfields.entrySet()) { + for (Map.Entry field : rfields.entrySet()) { Header headerSchema = new Header(); TypeSymbol fieldType = field.getValue().typeDescriptor(); String type = fieldType.typeKind().toString().trim().toLowerCase(Locale.ENGLISH); - Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(type); + Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(type); if (fieldType instanceof ArrayTypeSymbol) { ArrayTypeSymbol array = (ArrayTypeSymbol) fieldType; TypeSymbol itemType = array.memberTypeDescriptor(); @@ -1010,6 +1294,7 @@ private void extractResponseHeaders(Map headers, RecordFieldSymb /** * This function to normalized header key value to OAS key value. * ex: ballerina header key x\-rate\-limit\-id -> x-rate-limit-id + * * @param field header flied */ private String getValidHeaderKey(Map.Entry field) { diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java index eaa3a8aa5..c9f9b032f 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ConverterCommonUtils.java @@ -44,6 +44,7 @@ import io.ballerina.compiler.syntax.tree.RequiredParameterNode; import io.ballerina.compiler.syntax.tree.SeparatedNodeList; import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.SpecificFieldNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.openapi.converter.Constants; @@ -51,12 +52,15 @@ import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; +import io.ballerina.openapi.converter.service.OpenAPIComponentMapper; +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 io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.BooleanSchema; @@ -71,8 +75,6 @@ import org.apache.commons.io.FilenameUtils; import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -96,7 +98,6 @@ * Utilities used in Ballerina to OpenAPI converter. */ public class ConverterCommonUtils { - private static final String GENERATED_METHOD_PREFIX = "$gen$"; /** * Retrieves a matching OpenApi {@link Schema} for a provided ballerina type. @@ -104,8 +105,8 @@ public class ConverterCommonUtils { * @param type ballerina type name as a String * @return OpenApi {@link Schema} for type defined by {@code type} */ - public static Schema getOpenApiSchema(String type) { - Schema schema; + public static Schema getOpenApiSchema(String type) { + Schema schema; switch (type) { case Constants.STRING: case Constants.PLAIN: @@ -126,7 +127,7 @@ public static Schema getOpenApiSchema(String type) { case Constants.BYTE_ARRAY: case Constants.OCTET_STREAM: schema = new StringSchema(); - schema.setFormat("uuid"); + schema.setFormat("byte"); break; case Constants.NUMBER: case Constants.DECIMAL: @@ -151,7 +152,7 @@ public static Schema getOpenApiSchema(String type) { case Constants.XML: case Constants.JSON: default: - schema = new Schema(); + schema = new Schema<>(); break; } return schema; @@ -181,7 +182,7 @@ public static Schema getOpenApiSchema(SyntaxKind type) { break; case BYTE_TYPE_DESC: schema = new StringSchema(); - schema.setFormat("uuid"); + schema.setFormat("byte"); break; case DECIMAL_TYPE_DESC: schema = new NumberSchema(); @@ -195,7 +196,7 @@ public static Schema getOpenApiSchema(SyntaxKind type) { schema = new ObjectSchema(); break; default: - schema = new Schema(); + schema = new Schema<>(); break; } return schema; @@ -215,7 +216,7 @@ public static String getOperationId(String operationID) { } String[] split = operationID.split(Constants.SPECIAL_CHAR_REGEX); StringBuilder validName = new StringBuilder(); - for (String part: split) { + for (String part : split) { if (!part.isBlank()) { if (split.length > 1) { part = part.substring(0, 1).toUpperCase(Locale.ENGLISH) + @@ -228,7 +229,6 @@ public static String getOperationId(String operationID) { return operationID.substring(0, 1).toLowerCase(Locale.ENGLISH) + operationID.substring(1); } - /** * This util function uses to take the field value from annotation field. * @@ -252,9 +252,9 @@ public static Optional extractServiceAnnotationDetails(NodeList extractAnnotationFieldDetails(String annotationRefere MappingConstructorExpressionNode listOfAnnotValue = annotation.annotValue().get(); for (MappingFieldNode field : listOfAnnotValue.fields()) { SpecificFieldNode fieldNode = (SpecificFieldNode) field; - if (!((fieldNode).fieldName().toString().trim().equals(annotationField)) && + if (!((fieldNode).fieldName().toString().trim().equals(annotationField)) || fieldNode.valueExpr().isEmpty()) { continue; } ExpressionNode expressionNode = fieldNode.valueExpr().get(); if (expressionNode instanceof ListConstructorExpressionNode) { - SeparatedNodeList mimeList = ((ListConstructorExpressionNode) expressionNode).expressions(); + SeparatedNodeList mimeList = ((ListConstructorExpressionNode) expressionNode).expressions(); for (Object mime : mimeList) { if (!(mime instanceof BasicLiteralNode)) { continue; @@ -294,6 +294,7 @@ public static List extractAnnotationFieldDetails(String annotationRefere } return mediaTypes; } + /** * This function uses to take the service declaration node from given required node and return all the annotation * nodes that attached to service node. @@ -337,6 +338,7 @@ public static Optional extractCustomMediaType(FunctionDefinitionNode fun * 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); @@ -352,7 +354,7 @@ public TextRange textRange() { /** * Parse and get the {@link OpenAPI} for the given OpenAPI contract. * - * @param definitionURI URI for the OpenAPI contract + * @param definitionURI URI for the OpenAPI contract * @return {@link OASResult} OpenAPI model */ public static OASResult parseOpenAPIFile(String definitionURI) { @@ -377,19 +379,17 @@ public static OASResult parseOpenAPIFile(String definitionURI) { } String openAPIFileContent = null; try { - openAPIFileContent = Files.readString(Paths.get(definitionURI)); + openAPIFileContent = Files.readString(contractPath); } catch (IOException e) { DiagnosticMessages error = DiagnosticMessages.OAS_CONVERTOR_108; - ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode() - , error.getDescription(), null, e.toString()); + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), error.getDescription(), null, + e.toString()); diagnostics.add(diagnostic); } - SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(openAPIFileContent, null, - parseOptions); + SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(openAPIFileContent, null, parseOptions); if (!parseResult.getMessages().isEmpty()) { DiagnosticMessages error = DiagnosticMessages.OAS_CONVERTOR_112; - ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode() - , error.getDescription(), null); + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), error.getDescription(), null); diagnostics.add(diagnostic); return new OASResult(null, diagnostics); } @@ -409,12 +409,14 @@ public static String normalizeTitle(String serviceName) { if (path.isBlank()) { continue; } - stringBuilder.append(path.substring(0, 1).toUpperCase(Locale.ENGLISH) + path.substring(1)); + 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) + urlPaths[0].substring(1)); + stringBuilder.append(urlPaths[0].substring(0, 1).toUpperCase(Locale.ENGLISH)); + stringBuilder.append(urlPaths[0].substring(1)); title = stringBuilder.toString().trim(); } return title; @@ -423,12 +425,16 @@ public static String normalizeTitle(String serviceName) { /** * This util function is to check the given service is http service. * - * @param serviceNode Service node for analyse - * @param semanticModel Semantic model - * @return boolean output + * @param serviceNode Service node for analyse + * @param semanticModel Semantic model + * @return boolean output */ public static boolean isHttpService(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) { @@ -516,17 +522,21 @@ public static boolean containErrors(List diagnostics) { } public static String unescapeIdentifier(String parameterName) { - // NOTE: This is a temporary fix to decode unicode until we come up with a proper api. - // This already implemented API from {@link io.ballerina.identifier.Utils} can be access, if it is available - // in some which we can access in external class. That API is need to be implemented. - try { - Class uClass = Class.forName("io.ballerina.identifier.Utils"); - Method unescapeBallerina = uClass.getDeclaredMethod("unescapeBallerina", java.lang.String.class); - parameterName = (String) unescapeBallerina.invoke(null, parameterName); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | - InvocationTargetException e) { - return parameterName; + String unescapedParamName = IdentifierUtils.unescapeBallerina(parameterName); + return unescapedParamName.replaceAll("\\\\", "").replaceAll("'", ""); + } + + public static Schema handleReference(SemanticModel semanticModel, Components components, + SimpleNameReferenceNode record) { + Schema refSchema = new Schema<>(); + // Creating request body - required. + Optional symbol = semanticModel.symbol(record); + if (symbol.isPresent() && symbol.get() instanceof TypeSymbol) { + String recordName = record.name().toString().trim(); + OpenAPIComponentMapper componentMapper = new OpenAPIComponentMapper(components); + componentMapper.createComponentSchema(components.getSchemas(), (TypeSymbol) symbol.get()); + refSchema.set$ref(ConverterCommonUtils.unescapeIdentifier(recordName)); } - return parameterName.replaceAll("\\\\", "").replaceAll("'", ""); + return refSchema; } } diff --git a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java index f8fd3e76d..47bbf5768 100644 --- a/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java +++ b/openapi-bal-service/src/main/java/io/ballerina/openapi/converter/utils/ServiceToOpenAPIConverterUtils.java @@ -40,13 +40,15 @@ import io.ballerina.openapi.converter.diagnostic.DiagnosticMessages; import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; +import io.ballerina.openapi.converter.model.OASGenerationMetaInfo; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.model.OpenAPIInfo; +import io.ballerina.openapi.converter.service.ModuleMemberVisitor; import io.ballerina.openapi.converter.service.OpenAPIEndpointMapper; import io.ballerina.openapi.converter.service.OpenAPIServiceMapper; +import io.ballerina.projects.Module; +import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Location; -import io.swagger.v3.core.util.Json; -import io.swagger.v3.core.util.Yaml; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; @@ -57,6 +59,7 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -90,10 +93,10 @@ public class ServiceToOpenAPIConverterUtils { * @param inputPath - Input file path for resolve the annotation details * @return - {@link java.util.Map} with openAPI definitions for service nodes */ - public static List generateOAS3Definition(SyntaxTree syntaxTree, SemanticModel semanticModel, + public static List generateOAS3Definition(Project project, SyntaxTree syntaxTree, + SemanticModel semanticModel, String serviceName, Boolean needJson, Path inputPath) { - List endpoints = new ArrayList<>(); Map servicesToGenerate = new HashMap<>(); List availableService = new ArrayList<>(); List diagnostics = new ArrayList<>(); @@ -105,8 +108,7 @@ public static List generateOAS3Definition(SyntaxTree syntaxTree, Sema diagnostics.add(error); } else { ModulePartNode modulePartNode = syntaxTree.rootNode(); - extractListenersAndServiceNodes(serviceName, availableService, servicesToGenerate, modulePartNode, - endpoints, semanticModel); + extractServiceNodes(serviceName, availableService, servicesToGenerate, modulePartNode, semanticModel); // If there are no services found for a given service name. if (serviceName != null && servicesToGenerate.isEmpty()) { DiagnosticMessages messages = DiagnosticMessages.OAS_CONVERTOR_107; @@ -117,8 +119,15 @@ public static List generateOAS3Definition(SyntaxTree syntaxTree, Sema // Generating openapi specification for selected services for (Map.Entry serviceNode : servicesToGenerate.entrySet()) { String openApiName = getOpenApiFileName(syntaxTree.filePath(), serviceNode.getKey(), needJson); - OASResult oasDefinition = generateOAS(serviceNode.getValue(), endpoints, semanticModel, openApiName, - inputPath); + OASGenerationMetaInfo.OASGenerationMetaInfoBuilder builder = + new OASGenerationMetaInfo.OASGenerationMetaInfoBuilder(); + builder.setServiceDeclarationNode(serviceNode.getValue()) + .setSemanticModel(semanticModel) + .setOpenApiFileName(openApiName) + .setBallerinaFilePath(inputPath) + .setProject(project); + OASGenerationMetaInfo oasGenerationMetaInfo = builder.build(); + OASResult oasDefinition = generateOAS(oasGenerationMetaInfo); oasDefinition.setServiceName(openApiName); outputs.add(oasDefinition); } @@ -133,18 +142,11 @@ public static List generateOAS3Definition(SyntaxTree syntaxTree, Sema /** * Filter all the end points and service nodes. */ - private static void extractListenersAndServiceNodes(String serviceName, List availableService, - Map servicesToGenerate, - ModulePartNode modulePartNode, - List endpoints, - SemanticModel semanticModel) { + private static void extractServiceNodes(String serviceName, List availableService, + Map servicesToGenerate, + ModulePartNode modulePartNode, 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); - } if (syntaxKind.equals(SyntaxKind.SERVICE_DECLARATION)) { ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) node; if (isHttpService(serviceNode, semanticModel)) { @@ -191,43 +193,20 @@ private static void extractListenersAndServiceNodes(String serviceName, List endpoints, - SemanticModel semanticModel, String openApiName) { - Optional openapi = generateOAS(serviceDeclarationNode, endpoints, semanticModel, openApiName, - null).getOpenAPI(); - if (openapi.isPresent()) { - OpenAPI openAPI = openapi.get(); - if (openAPI.getInfo().getTitle() == null || openAPI.getInfo().getTitle().equals(SLASH)) { - openAPI.getInfo().setTitle(normalizeTitle(openApiName)); - } - return needJson ? Json.pretty(openAPI) : Yaml.pretty(openAPI); - } - return "Error while generating openAPI contract"; - } - /** * Provides an instance of {@code OASResult}, 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 openApiFileName OpenAPI file name - * @param ballerinaFilePath Input ballerina file Path + * @param oasGenerationMetaInfo Includes the service definition node, endpoints, semantic model, openapi file + * name and ballerina file path * @return {@code OASResult} */ - public static OASResult generateOAS(ServiceDeclarationNode serviceDefinition, - List endpoints, SemanticModel semanticModel, - String openApiFileName, Path ballerinaFilePath) { + public static OASResult generateOAS(OASGenerationMetaInfo oasGenerationMetaInfo) { + ServiceDeclarationNode serviceDefinition = oasGenerationMetaInfo.getServiceDeclarationNode(); + LinkedHashSet listeners = collectListeners(oasGenerationMetaInfo.getProject());; + SemanticModel semanticModel = oasGenerationMetaInfo.getSemanticModel(); + String openApiFileName = oasGenerationMetaInfo.getOpenApiFileName(); + Path ballerinaFilePath = oasGenerationMetaInfo.getBallerinaFilePath(); // 01.Fill the openAPI info section OASResult oasResult = fillOpenAPIInfoSection(serviceDefinition, semanticModel, openApiFileName, ballerinaFilePath); @@ -237,7 +216,7 @@ public static OASResult generateOAS(ServiceDeclarationNode serviceDefinition, // Take base path of service OpenAPIServiceMapper openAPIServiceMapper = new OpenAPIServiceMapper(semanticModel); // 02. Filter and set the ServerURLs according to endpoints. Complete the server section in OAS - openapi = OpenAPIEndpointMapper.ENDPOINT_MAPPER.getServers(openapi, endpoints, serviceDefinition); + openapi = OpenAPIEndpointMapper.ENDPOINT_MAPPER.getServers(openapi, listeners, serviceDefinition); // 03. Filter path and component sections in OAS. // Generate openApi string for the mentioned service name. openapi = openAPIServiceMapper.convertServiceToOpenAPI(serviceDefinition, openapi); @@ -290,19 +269,31 @@ private static OASResult fillOpenAPIInfoSection(ServiceDeclarationNode serviceNo ballerinaFilePath); return normalizeInfoSection(openapiFileName, currentServiceName, version, oasResult); } else { - openAPI.setInfo(new Info().version(version).title(normalizeTitle(currentServiceName))); + setInfoDetailsIfServiceNameAbsent(openapiFileName, openAPI, currentServiceName, version); } + } else { + setInfoDetailsIfServiceNameAbsent(openapiFileName, openAPI, currentServiceName, version); } } - } else if (currentServiceName.equals(SLASH) || currentServiceName.isBlank()) { - openAPI.setInfo(new Info().version(version).title(normalizeTitle(openapiFileName))); } else { - openAPI.setInfo(new Info().version(version).title(normalizeTitle(currentServiceName))); + setInfoDetailsIfServiceNameAbsent(openapiFileName, openAPI, currentServiceName, version); } return new OASResult(openAPI, diagnostics); } + /** + * Generates openAPI Info section when the service base path is absent or `/`. + */ + private static void setInfoDetailsIfServiceNameAbsent(String openapiFileName, OpenAPI openAPI, + String currentServiceName, String version) { + if (currentServiceName.equals(SLASH) || currentServiceName.isBlank()) { + openAPI.setInfo(new Info().version(version).title(normalizeTitle(openapiFileName))); + } else { + openAPI.setInfo(new Info().version(version).title(normalizeTitle(currentServiceName))); + } + } + // Finalize the openAPI info section private static OASResult normalizeInfoSection(String openapiFileName, String currentServiceName, String version, OASResult oasResult) { @@ -492,4 +483,23 @@ private static OASResult resolveContractPath(List di } return new OASResult(openAPI, diagnostics); } + + /** + * Travers every syntax tree and collect all the listener nodes. + * + * @param project - current project + */ + public static LinkedHashSet collectListeners(Project project) { + ModuleMemberVisitor balNodeVisitor = new ModuleMemberVisitor(); + LinkedHashSet listeners = new LinkedHashSet<>(); + project.currentPackage().moduleIds().forEach(moduleId -> { + Module module = project.currentPackage().module(moduleId); + module.documentIds().forEach(documentId -> { + SyntaxTree syntaxTreeDoc = module.document(documentId).syntaxTree(); + syntaxTreeDoc.rootNode().accept(balNodeVisitor); + listeners.addAll(balNodeVisitor.getListenerDeclarationNodes()); + }); + }); + return listeners; + } } diff --git a/openapi-bal-service/src/main/java/module-info.java b/openapi-bal-service/src/main/java/module-info.java index cd9e37344..1b9926b0d 100644 --- a/openapi-bal-service/src/main/java/module-info.java +++ b/openapi-bal-service/src/main/java/module-info.java @@ -15,22 +15,19 @@ */ module io.ballerina.openapi.converter { - requires com.fasterxml.jackson.core; - requires com.fasterxml.jackson.databind; requires handlebars; requires info.picocli; requires io.ballerina.lang; requires io.ballerina.parser; requires io.ballerina.tools.api; + requires io.ballerina.runtime; requires io.swagger.v3.core; requires io.swagger.v3.oas.models; requires java.ws.rs; requires jsr305; requires org.apache.commons.io; requires org.slf4j; - requires swagger.core; requires swagger.parser; - requires swagger.models; requires swagger.parser.core; requires swagger.parser.v2.converter; requires swagger.parser.v3; diff --git a/openapi-build-extension/build.gradle b/openapi-build-extension/build.gradle index eeac5dc06..db2d81061 100644 --- a/openapi-build-extension/build.gradle +++ b/openapi-build-extension/build.gradle @@ -18,7 +18,7 @@ apply from: "$rootDir/gradle/javaProject.gradle" apply plugin: "com.github.johnrengelman.shadow" -apply plugin: "java" +apply plugin: "java-library" description = "Ballerina - OpenAPI Build Extensions" @@ -32,7 +32,7 @@ configurations { dependencies { implementation "io.swagger.core.v3:swagger-models" - implementation ("io.swagger.parser.v3:swagger-parser-v2-converter") { + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { exclude group: "io.swagger", module: "swagger-compat-spec-parser" exclude group: "org.slf4j", module: "slf4j-ext" exclude group: "javax.validation", module: "validation-api" diff --git a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java index 03a0d2694..516fe6c0a 100644 --- a/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java +++ b/openapi-build-extension/src/main/java/io/ballerina/openapi/build/HttpServiceAnalysisTask.java @@ -19,7 +19,6 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.api.symbols.ServiceDeclarationSymbol; import io.ballerina.compiler.api.symbols.Symbol; -import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; import io.ballerina.compiler.syntax.tree.ModulePartNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; @@ -28,6 +27,7 @@ import io.ballerina.openapi.converter.diagnostic.DiagnosticMessages; import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; +import io.ballerina.openapi.converter.model.OASGenerationMetaInfo; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.service.OpenAPIEndpointMapper; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; @@ -91,7 +91,6 @@ public void perform(SyntaxNodeAnalysisContext context) { Optional path = currentPackage.project().documentPath(context.documentId()); Path inputPath = path.orElse(null); ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) context.node(); - List endpoints = new ArrayList<>(); Map services = new HashMap<>(); List diagnostics = new ArrayList<>(); @@ -101,9 +100,13 @@ public void perform(SyntaxNodeAnalysisContext context) { } else if (isHttpService(serviceNode, semanticModel)) { Optional serviceSymbol = semanticModel.symbol(serviceNode); if (serviceSymbol.isPresent() && serviceSymbol.get() instanceof ServiceDeclarationSymbol) { - extractListenersAndServiceNodes(syntaxTree.rootNode(), endpoints, services, semanticModel); - OASResult oasResult = ServiceToOpenAPIConverterUtils.generateOAS(serviceNode, endpoints, - semanticModel, services.get(serviceSymbol.get().hashCode()), inputPath); + extractServiceNodes(syntaxTree.rootNode(), services, semanticModel); + OASGenerationMetaInfo.OASGenerationMetaInfoBuilder builder = + new OASGenerationMetaInfo.OASGenerationMetaInfoBuilder(); + builder.setServiceDeclarationNode(serviceNode).setSemanticModel(semanticModel) + .setOpenApiFileName(services.get(serviceSymbol.get().hashCode())) + .setBallerinaFilePath(inputPath).setProject(project); + OASResult oasResult = ServiceToOpenAPIConverterUtils.generateOAS(builder.build()); oasResult.setServiceName(constructFileName(syntaxTree, services, serviceSymbol.get())); writeOpenAPIYaml(outPath, oasResult, diagnostics); } @@ -159,18 +162,11 @@ private void writeOpenAPIYaml(Path outPath, OASResult oasResult, List endpoints, - Map services, - SemanticModel semanticModel) { + private static void extractServiceNodes(ModulePartNode modulePartNode, Map services, + SemanticModel semanticModel) { List allServices = new ArrayList<>(); 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); - } if (syntaxKind.equals(SyntaxKind.SERVICE_DECLARATION)) { ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) node; if (isHttpService(serviceNode, semanticModel)) { diff --git a/openapi-cli/build.gradle b/openapi-cli/build.gradle index ab24791f8..9f5a9d20f 100644 --- a/openapi-cli/build.gradle +++ b/openapi-cli/build.gradle @@ -17,7 +17,7 @@ apply from: "$rootDir/gradle/javaProject.gradle" apply plugin: "com.github.johnrengelman.shadow" -apply plugin: "java" +apply plugin: "java-library" description = "Ballerina - OpenAPI Tooling - OpenAPI to Ballerina" @@ -31,13 +31,13 @@ configurations { dependencies { implementation project(':openapi-bal-service') - implementation "com.fasterxml.jackson.core:jackson-databind" - implementation "io.swagger.core.v3:swagger-models" - implementation ("io.swagger.parser.v3:swagger-parser-v2-converter") { + implementation project(':openapi-core') + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { exclude group: "io.swagger", module: "swagger-compat-spec-parser" exclude group: "org.slf4j", module: "slf4j-ext" exclude group: "javax.validation", module: "validation-api" } + implementation "io.swagger.core.v3:swagger-models" implementation "javax.ws.rs:javax.ws.rs-api" implementation "com.github.jknack:handlebars" implementation "info.picocli:picocli" @@ -49,6 +49,7 @@ dependencies { implementation "io.ballerina.stdlib:http-native" implementation "com.google.code.findbugs:jsr305" testImplementation "org.testng:testng" + testImplementation 'junit:junit:4.13.1' balTools ("org.ballerinalang:jballerina-tools:${ballerinaLangVersion}") { transitive = false @@ -84,6 +85,7 @@ task copyStdlibs(type: Copy) { dependsOn(unpackStdLibs) def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE /* Standard Libraries */ configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/ErrorMessages.java b/openapi-cli/src/main/java/io/ballerina/openapi/ErrorMessages.java deleted file mode 100644 index 3914957b8..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/ErrorMessages.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2019, 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.openapi; - -/** - * Container for error messages of the OpenAPI validator plugin. - */ -public class ErrorMessages { - - public static String invalidFilePath(String path) { - return String.format("OpenAPI 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."; - } - - public static String invalidFile(String path) { - return String.format("Invalid swagger file in the given location:%n%s", path); - } - - public static String invalidPathParamType(String parameterName) { - return String.format("Invalid path parameter data type for the parameter: '%s'", parameterName); - } - - static String undocumentedResourcePath(String path) { - return String.format("Ballerina service contains a Resource that is not" - + " documented in the OpenAPI contract." - + " Error Resource path '%s'", path); - } - - static String undocumentedResourceParameter(String paramName, String method, String path) { - return String.format("'%s' parameter for the method '%s' " + - "of the resource associated with the path '%s' " + - "is not documented in the OpenAPI contract", paramName, method, path); - } - - static String undocumentedResourceMethods(String methods, String path) { - return String.format("OpenAPI contract doesn't contain the" + - " documentation for http method(s) '%s' for the path '%s'", methods, path); - } - - static String unimplementedOpenAPIPath(String path) { - return String.format("Couldn't find a Ballerina service resource for the path '%s' " + - "which is documented in the OpenAPI contract", path); - } - - static String unimplementedOpenAPIOperationsForPath(String methods, String path) { - return String.format("Couldn't find Ballerina service resource(s) for http method(s) '%s' " + - "for the path '%s' which is documented in the OpenAPI contract", methods, path); - } - - static String unimplementedParameterForOperation(String paramName, String method, String path) { - return String.format("Couldn't find '%s' parameter in the Ballerina service resource for the method '%s' " + - "of the path '%s' which is documented in the OpenAPI contract", paramName, method, path); - } - - static String undocumentedFieldInRecordParam(String fieldName, String paramName, String method, String path) { - return String.format("The '%s' field in the '%s' type record of the parameter " + - "is not documented in the OpenAPI contract for the method '%s' of the path '%s'", - fieldName, paramName, method, path); - } - - static String unimplementedFieldInOperation(String fieldName, String paramName, String operation, String path) { - return String.format("Couldn't find the '%s' field in the record type of the parameter '%s' " + - "for the method '%s' of the path '%s' which is documented in the OpenAPI contract", - fieldName, paramName, operation, path); - } - - static String tagFilterEnable() { - return String.format("Both Tags and excludeTags fields include the same tag(s). Make sure to use one" + - " field of tag filtering when using the OpenAPI annotation. "); - } - - static String operationFilterEnable() { - return String.format("Both Operations and excludeOperations fields include" + - " the same operation(s). Make sure to use one field of operation filtering" + - " when using the OpenAPI annotation."); - } - - static String typeMismatching(String fieldName, String openapiType, String ballerinType, - String method, String path) { - return String.format("Type mismatch with parameter '%s' for the method" + - " '%s' of the path '%s'.In OpenAPI contract its type is '%s' and resources type is '%s'. ", - fieldName, method, path, openapiType, ballerinType); - } - - static String typeMismatchingRecord(String fieldName, String paramName, String openapiType, String ballerinType, - String method, String path) { - return String.format("Type mismatching '%s' field in the record type of the parameter '%s' for the method" + - " '%s' of the path '%s'.In OpenAPI contract its type is '%s' and resources type is '%s'. ", - fieldName, paramName, method, path, openapiType , ballerinType); - } - - static String typeMismatchOneOfObject(String fieldName, String paramName, String openapiType, String ballerinType, - String method, String path) { - return String.format("Type mismatch with '%s' field in the object type of the parameter '%s' for the method" + - " '%s' of the path '%s'.OpenAPI object schema expected '%s' type and resources has '%s' type for field.", - fieldName, paramName, method, path, openapiType, ballerinType); - } - - static String typeMismatchOneOfRecord(String fieldName, String paramName, String openapiType, String ballerinType, - String method, String path) { - return String.format("Type mismatch with '%s' field in the record type of the parameter '%s' " + - "for the method '%s' of the path '%s'.OpenAPI object schema expected '%s' " + - "type and resources has '%s' type for field.", - fieldName, paramName, method, path, openapiType, ballerinType); - } - -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/BallerinaCodeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/BallerinaCodeGenerator.java new file mode 100644 index 000000000..61c195de5 --- /dev/null +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/BallerinaCodeGenerator.java @@ -0,0 +1,472 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.cmd; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.converter.utils.CodegenUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.BallerinaTestGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.BallerinaServiceObjectGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.openapi.core.model.GenSrcFile; +import io.swagger.v3.oas.models.OpenAPI; +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.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static io.ballerina.openapi.cmd.CmdConstants.CLIENT_FILE_NAME; +import static io.ballerina.openapi.cmd.CmdConstants.CONFIG_FILE_NAME; +import static io.ballerina.openapi.cmd.CmdConstants.DEFAULT_CLIENT_PKG; +import static io.ballerina.openapi.cmd.CmdConstants.DEFAULT_MOCK_PKG; +import static io.ballerina.openapi.cmd.CmdConstants.GenType.GEN_BOTH; +import static io.ballerina.openapi.cmd.CmdConstants.GenType.GEN_CLIENT; +import static io.ballerina.openapi.cmd.CmdConstants.GenType.GEN_SERVICE; +import static io.ballerina.openapi.cmd.CmdConstants.OAS_PATH_SEPARATOR; +import static io.ballerina.openapi.cmd.CmdConstants.TEST_DIR; +import static io.ballerina.openapi.cmd.CmdConstants.TEST_FILE_NAME; +import static io.ballerina.openapi.cmd.CmdConstants.TYPE_FILE_NAME; +import static io.ballerina.openapi.cmd.CmdConstants.UNTITLED_SERVICE; +import static io.ballerina.openapi.cmd.CmdConstants.UTIL_FILE_NAME; +import static io.ballerina.openapi.cmd.CmdUtils.setGeneratedFileName; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_FILE_HEADER; +import static io.ballerina.openapi.core.GeneratorConstants.DO_NOT_MODIFY_FILE_HEADER; + +/** + * This class generates Ballerina Services/Clients for a provided OAS definition. + * + * @since 1.3.0 + */ +public class BallerinaCodeGenerator { + private String srcPackage; + private String licenseHeader = ""; + private boolean includeTestFiles; + + private static final PrintStream outStream = System.err; + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + *

Method can be user for generating Ballerina mock services and clients

+ */ + public void generateClientAndService(String definitionPath, String serviceName, + String outPath, Filter filter, boolean nullable, + boolean isResource, boolean generateServiceType, + boolean generateWithoutDataBinding) + throws IOException, FormatterException, + io.ballerina.openapi.core.exception.BallerinaOpenApiException { + Path srcPath = Paths.get(outPath); + Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); + + List sourceFiles = new ArrayList<>(); + Path openAPIPath = Path.of(definitionPath); + // Normalize OpenAPI definition, in the client generation we suppose to terminate code generation when the + // absence of the operationId in operation. Therefor we enable client flag true as default code generation. + // if resource is enabled, we avoid checking operationId. + OpenAPI openAPIDef = GeneratorUtils.normalizeOpenAPI(openAPIPath, !isResource); + + // Generate service + String concatTitle = serviceName.toLowerCase(Locale.ENGLISH); + String srcFile = concatTitle + "_service.bal"; + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPIDef) + .withFilters(filter) + .withNullable(nullable) + .withGenerateServiceType(generateServiceType) + .withGenerateWithoutDataBinding(generateWithoutDataBinding) + .build(); + BallerinaServiceGenerator serviceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + String serviceContent = Formatter.format + (serviceGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, srcFile, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + serviceContent)); + + if (generateServiceType) { + BallerinaServiceObjectGenerator ballerinaServiceObjectGenerator = new + BallerinaServiceObjectGenerator(serviceGenerator.getFunctionList()); + String serviceType = Formatter.format(ballerinaServiceObjectGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, + "service_type.bal", (licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : + licenseHeader) + serviceType)); + } + // Generate client. + // Generate ballerina client remote. + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withNullable(nullable) + .withPlugin(false) + .withOpenAPI(openAPIDef) + .withResourceMode(isResource).build(); + + BallerinaClientGenerator clientGenerator = new BallerinaClientGenerator(oasClientConfig); + String clientContent = Formatter.format(clientGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CLIENT_FILE_NAME, + (licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : licenseHeader) + clientContent)); + String utilContent = Formatter.format(clientGenerator + .getBallerinaUtilGenerator() + .generateUtilSyntaxTree()).toString(); + if (!utilContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.UTIL_SRC, srcPackage, UTIL_FILE_NAME, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + utilContent)); + } + + //Update type definition list + List preGeneratedTypeDefNodes = new ArrayList<>( + clientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + List typeInclusionRecords = serviceGenerator.getTypeInclusionRecords(); + List typeDefinitionNodeList = clientGenerator.getTypeDefinitionNodeList(); + preGeneratedTypeDefNodes.addAll(typeInclusionRecords); + preGeneratedTypeDefNodes.addAll(typeDefinitionNodeList); + + // Generate ballerina types. + // Generate ballerina records to represent schemas. + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + openAPIDef, nullable, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + String schemaContent = Formatter.format(schemaSyntaxTree).toSourceCode(); + + if (filter.getTags().size() > 0) { + // Remove unused records and enums when generating the client by the tags given. + schemaContent = GeneratorUtils.removeUnusedEntities(schemaSyntaxTree, clientContent, schemaContent, + serviceContent); + } + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + schemaContent)); + } + + // Generate test boilerplate code for test cases + if (this.includeTestFiles) { + BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(clientGenerator); + String testContent = Formatter.format(ballerinaTestGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TEST_FILE_NAME, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + testContent)); + + String configContent = ballerinaTestGenerator.getConfigTomlFile(); + if (!configContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, + CONFIG_FILE_NAME, configContent)); + } + } + + List newGenFiles = sourceFiles.stream() + .filter(distinctByKey(GenSrcFile::getFileName)) + .collect(Collectors.toList()); + + writeGeneratedSources(newGenFiles, srcPath, implPath, GEN_BOTH); + } + + public static Predicate distinctByKey( + Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + * Method can be user for generating Ballerina clients. + * + * @param definitionPath Input Open Api Definition file path + * @param outPath Destination file path to save generated source files. If not provided + * {@code definitionPath} will be used as the default destination path + * @param filter For take the tags and operation option values + * @param nullable Enable nullable option for make record field optional + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when code generator fails + */ + public void generateClient(String definitionPath, String outPath, Filter filter, boolean nullable, + boolean isResource) + throws IOException, BallerinaOpenApiException, FormatterException { + Path srcPath = Paths.get(outPath); + Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); + List genFiles = generateClientFiles(Paths.get(definitionPath), filter, nullable, isResource); + writeGeneratedSources(genFiles, srcPath, implPath, GEN_CLIENT); + } + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + * Method can be user for generating Ballerina clients. + * + * @param definitionPath Input Open Api Definition file path + * @param serviceName service name for the generated service + * @param outPath Destination file path to save generated source files. If not provided + * {@code definitionPath} will be used as the default destination path + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when code generator fails + */ + public void generateService(String definitionPath, String serviceName, String outPath, Filter filter, + boolean nullable, boolean generateServiceType, boolean generateWithoutDataBinding) + throws IOException, BallerinaOpenApiException, FormatterException { + Path srcPath = Paths.get(outPath); + Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); + List genFiles = generateBallerinaService(Paths.get(definitionPath), serviceName, + filter, nullable, generateServiceType, generateWithoutDataBinding); + writeGeneratedSources(genFiles, srcPath, implPath, GEN_SERVICE); + } + + private void writeGeneratedSources(List sources, Path srcPath, Path implPath, + CmdConstants.GenType type) + throws IOException { + // Remove old generated file with same name + List listFiles = new ArrayList<>(); + 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 = implPath.resolve(file.getFileName()); + if (Files.notExists(filePath)) { + String fileContent = 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 + OAS_PATH_SEPARATOR + TEST_DIR)); + filePath = Paths.get(srcPath.resolve(TEST_DIR + OAS_PATH_SEPARATOR + + file.getFileName()).toFile().getCanonicalPath()); + } else { + filePath = Paths.get(srcPath.resolve(file.getFileName()).toFile().getCanonicalPath()); + } + String fileContent = file.getContent(); + CodegenUtils.writeFile(filePath, fileContent); + } + } + + //This will print the generated files to the console + if (type.equals(GEN_SERVICE)) { + outStream.println("Service generated successfully and the OpenAPI contract is copied to path " + srcPath + + "."); + } else if (type.equals(GEN_CLIENT)) { + 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. + * + * @return generated source files as a list of {@link GenSrcFile} + * @throws IOException when code generation with specified templates fails + */ + private List generateClientFiles(Path openAPI, Filter filter, boolean nullable, boolean isResource) + throws IOException, BallerinaOpenApiException, FormatterException { + if (srcPackage == null || srcPackage.isEmpty()) { + srcPackage = DEFAULT_CLIENT_PKG; + } + List sourceFiles = new ArrayList<>(); + // Normalize OpenAPI definition + OpenAPI openAPIDef = GeneratorUtils.normalizeOpenAPI(openAPI, !isResource); + // Generate ballerina service and resources. + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withNullable(nullable) + .withPlugin(false) + .withOpenAPI(openAPIDef) + .withResourceMode(isResource) + .build(); + //Take default DO NOT modify + licenseHeader = licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : licenseHeader; + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + String mainContent = Formatter.format(ballerinaClientGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CLIENT_FILE_NAME, + licenseHeader + mainContent)); + String utilContent = Formatter.format( + ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree()).toString(); + if (!utilContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.UTIL_SRC, srcPackage, UTIL_FILE_NAME, + licenseHeader + utilContent)); + } + + List preGeneratedTypeDefNodes = new ArrayList<>( + ballerinaClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList()); + // Generate ballerina records to represent schemas. + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + openAPIDef, nullable, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + String schemaContent = Formatter.format(schemaSyntaxTree).toSourceCode(); + if (filter.getTags().size() > 0) { + // Remove unused records and enums when generating the client by the tags given. + schemaContent = GeneratorUtils.removeUnusedEntities(schemaSyntaxTree, mainContent, schemaContent, null); + } + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, + licenseHeader + schemaContent)); + } + + // Generate test boilerplate code for test cases + if (this.includeTestFiles) { + BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(ballerinaClientGenerator); + String testContent = Formatter.format(ballerinaTestGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TEST_FILE_NAME, + licenseHeader + testContent)); + + String configContent = ballerinaTestGenerator.getConfigTomlFile(); + if (!configContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, + CONFIG_FILE_NAME, configContent)); + } + } + + return sourceFiles; + } + + + public List generateBallerinaService(Path openAPI, String serviceName, + Filter filter, boolean nullable, boolean generateServiceType, + boolean generateWithoutDataBinding) + throws IOException, FormatterException, BallerinaOpenApiException { + if (srcPackage == null || srcPackage.isEmpty()) { + srcPackage = DEFAULT_MOCK_PKG; + } + OpenAPI openAPIDef = GeneratorUtils.normalizeOpenAPI(openAPI, false); + if (openAPIDef.getInfo() == null) { + throw new BallerinaOpenApiException("Info section of the definition file cannot be empty/null: " + + openAPI); + } + + if (openAPIDef.getInfo().getTitle().isBlank() && (serviceName == null || serviceName.isBlank())) { + openAPIDef.getInfo().setTitle(UNTITLED_SERVICE); + } else { + openAPIDef.getInfo().setTitle(serviceName); + } + + List sourceFiles = new ArrayList<>(); + String concatTitle = serviceName == null ? + openAPIDef.getInfo().getTitle().toLowerCase(Locale.ENGLISH) : + serviceName.toLowerCase(Locale.ENGLISH); + String srcFile = concatTitle + "_service.bal"; + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPIDef) + .withFilters(filter) + .withNullable(nullable) + .withGenerateServiceType(generateServiceType) + .withGenerateWithoutDataBinding(generateWithoutDataBinding) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + String mainContent = Formatter.format(ballerinaServiceGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, srcFile, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + mainContent)); + List preGeneratedTypeDefNodes = new ArrayList<>( + ballerinaServiceGenerator.getTypeInclusionRecords()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + openAPIDef, nullable, preGeneratedTypeDefNodes); + String schemaContent = Formatter.format( + ballerinaSchemaGenerator.generateSyntaxTree()).toSourceCode(); + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TYPE_FILE_NAME, + (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + schemaContent)); + } + if (generateServiceType) { + BallerinaServiceObjectGenerator ballerinaServiceObjectGenerator = new + BallerinaServiceObjectGenerator(ballerinaServiceGenerator.getFunctionList()); + String serviceType = Formatter.format(ballerinaServiceObjectGenerator.generateSyntaxTree()).toSourceCode(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, + "service_type.bal", + (licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : licenseHeader) + serviceType)); + } + return sourceFiles; + } + + /** + * Set the content of license header. + * + * @param licenseHeader license header value received from command line. + */ + public void setLicenseHeader(String licenseHeader) { + this.licenseHeader = licenseHeader; + } + + /** + * set whether to add test files or not. + * + * @param includeTestFiles value received from command line by "--with tests" + */ + public void setIncludeTestFiles(boolean includeTestFiles) { + this.includeTestFiles = includeTestFiles; + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdConstants.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdConstants.java index 61e4b4a45..d3bdd4224 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdConstants.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdConstants.java @@ -17,6 +17,10 @@ */ package io.ballerina.openapi.cmd; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + /** * Constants for openapi commands. * @@ -26,4 +30,176 @@ public class CmdConstants { public static final String RESOURCE = "resource"; public static final String REMOTE = "remote"; public static final String SERVICE = "service"; + public static final String CLIENT = "client"; + + /** + * 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; + } + } + + /** + * Enum to select the relevant ballerina http auth record. + */ + public enum AuthConfigTypes { + BASIC("http:CredentialsConfig"), + BEARER("http:BearerTokenConfig"), + CLIENT_CREDENTIAL("http:OAuth2ClientCredentialsGrantConfig"), + CUSTOM_CLIENT_CREDENTIAL("OAuth2ClientCredentialsGrantConfig"), + REFRESH_TOKEN("http:OAuth2RefreshTokenGrantConfig"), + CUSTOM_REFRESH_TOKEN("OAuth2RefreshTokenGrantConfig"), + PASSWORD("http:OAuth2PasswordGrantConfig"), + CUSTOM_PASSWORD("OAuth2PasswordGrantConfig"); + + private final String authType; + + AuthConfigTypes(String authType) { + this.authType = authType; + } + + public String getValue() { + return authType; + } + } + + public static final String TYPE_FILE_NAME = "types.bal"; + public static final String CLIENT_FILE_NAME = "client.bal"; + public static final String UTIL_FILE_NAME = "utils.bal"; + public static final String TEST_FILE_NAME = "test.bal"; + public static final String SERVICE_FILE_NAME = "service.bal"; + public static final String CONFIG_FILE_NAME = "Config.toml"; + public static final String BALLERINA_TOML = "Ballerina.toml"; + public static final String BALLERINA_TOML_CONTENT = "[package]\n" + + "org= \"ballerina\"\n" + + "name= \"testopenapi\"\n" + + "version= \"0.0.0\"\n"; + + public static final String DEFAULT_CLIENT_PKG = "client"; + public static final String DEFAULT_MOCK_PKG = "mock"; + public static final String OAS_PATH_SEPARATOR = "/"; + public static final String UNTITLED_SERVICE = "UntitledAPI"; + //ClientCode generator + public static final String HTTP = "http"; + public static final String URL = "url"; + 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 IDENTIFIER = "identifier"; + public static final String TYPE_NAME = "typeName"; + public static final String DOUBLE = "double"; + public static final String FLOAT = "float"; + public static final String MIME = "mime"; + + // auth related constants + public static final String API_KEY = "apikey"; + + //Http Methods + public static final String POST = "post"; + public static final String GET = "get"; + public static final String PUT = "put"; + public static final String DELETE = "delete"; + public static final String PATCH = "patch"; + public static final String HEAD = "head"; + public static final String OPTIONS = "options"; + /** + * Util for select http keywords with http codes. + * + * @param code http code. + * @return Http identification word. + */ + public static final Map HTTP_CODES_DES; + + static { + Map httpCodeMap = new HashMap<>(); + httpCodeMap.put("100", "Continue"); + httpCodeMap.put("101", "SwitchingProtocols"); + httpCodeMap.put("200", "Ok"); + httpCodeMap.put("201", "Created"); + httpCodeMap.put("202", "Accepted"); + httpCodeMap.put("203", "NonAuthoritativeInformation"); + httpCodeMap.put("204", "NoContent"); + httpCodeMap.put("205", "RestContent"); + httpCodeMap.put("206", "PartialContent"); + httpCodeMap.put("300", "MultipleChoices"); + httpCodeMap.put("301", "MovedPermanently"); + httpCodeMap.put("302", "Found"); + httpCodeMap.put("303", "SeeOther"); + httpCodeMap.put("304", "NotModified"); + httpCodeMap.put("305", "UseProxy"); + httpCodeMap.put("307", "TemporaryRedirect"); + httpCodeMap.put("308", "PermanentRedirect"); + httpCodeMap.put("400", "BadRequest"); + httpCodeMap.put("401", "Unauthorized"); + httpCodeMap.put("402", "PaymentRequired"); + httpCodeMap.put("403", "Forbidden"); + httpCodeMap.put("404", "NotFound"); + httpCodeMap.put("405", "MethodNotAllowed"); + httpCodeMap.put("406", "NotAcceptable"); + httpCodeMap.put("407", "ProxyAuthenticationRequired"); + httpCodeMap.put("408", "RequestTimeOut"); + httpCodeMap.put("409", "Conflict"); + httpCodeMap.put("410", "Gone"); + httpCodeMap.put("411", "LengthRequired"); + httpCodeMap.put("412", "PreconditionFailed"); + httpCodeMap.put("413", "PayloadTooLarge"); + httpCodeMap.put("414", "UriTooLong"); + httpCodeMap.put("415", "UnsupportedMediaType"); + httpCodeMap.put("416", "RangeNotSatisfiable"); + httpCodeMap.put("417", "ExpectationFailed"); + httpCodeMap.put("426", "UpgradeRequired"); + httpCodeMap.put("429", "TooManyRequests"); + httpCodeMap.put("431", "RequestHeaderFieldsTooLarge"); + httpCodeMap.put("500", "InternalServerError"); + httpCodeMap.put("501", "NotImplemented"); + httpCodeMap.put("502", "BadGateway"); + httpCodeMap.put("503", "ServiceUnavailable"); + httpCodeMap.put("504", "GatewayTimeOut"); + httpCodeMap.put("505", "HttpVersionNotSupported"); + HTTP_CODES_DES = Collections.unmodifiableMap(httpCodeMap); + } + + public static final String NUMBER = "number"; + public static final String BAL_EXTENSION = ".bal"; + public static final String JSON_EXTENSION = ".json"; + public static final String YAML_EXTENSION = ".yaml"; + public static final String YML_EXTENSION = ".yml"; + + 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[]"); + TYPE_MAP = Collections.unmodifiableMap(typeMap); + } + + // OS specific line separator + public static final String LINE_SEPARATOR = System.lineSeparator(); + public static final String DOUBLE_LINE_SEPARATOR = LINE_SEPARATOR + LINE_SEPARATOR; + } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdUtils.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdUtils.java index f38bfb694..3da5cd711 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdUtils.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CmdUtils.java @@ -18,11 +18,25 @@ package io.ballerina.openapi.cmd; import io.ballerina.openapi.converter.utils.ConverterCommonUtils; +import io.ballerina.openapi.core.ErrorMessages; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.model.GenSrcFile; import io.ballerina.tools.diagnostics.DiagnosticInfo; import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.ballerina.tools.diagnostics.Location; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.OpenAPIV3Parser; +import io.swagger.v3.parser.core.models.ParseOptions; +import io.swagger.v3.parser.core.models.SwaggerParseResult; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collections; +import java.util.List; + +import static io.ballerina.openapi.core.GeneratorConstants.LINE_SEPARATOR; /** * Contains all the util functions used for openapi commands. @@ -36,10 +50,60 @@ public class CmdUtils { */ public static OpenAPIDiagnostic constructOpenAPIDiagnostic(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 OpenAPIDiagnostic(diagnosticInfo, location, Collections.emptyList(), args); } + + /** + * Util for take OpenApi spec from given yaml file. + */ + public static OpenAPI getOpenAPIFromOpenAPIV3Parser(Path definitionPath) throws + IOException, BallerinaOpenApiException { + + Path contractPath = java.nio.file.Paths.get(definitionPath.toString()); + if (!Files.exists(contractPath)) { + throw new BallerinaOpenApiException(ErrorMessages.invalidFilePath(definitionPath.toString())); + } + if (!(definitionPath.toString().endsWith(".yaml") || definitionPath.toString().endsWith(".json") || + definitionPath.toString().endsWith(".yml"))) { + throw new BallerinaOpenApiException(ErrorMessages.invalidFileType()); + } + String openAPIFileContent = Files.readString(definitionPath); + ParseOptions parseOptions = new ParseOptions(); + parseOptions.setResolve(true); + parseOptions.setFlatten(true); + SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(openAPIFileContent, null, parseOptions); + if (!parseResult.getMessages().isEmpty()) { + StringBuilder errorMessage = new StringBuilder("OpenAPI definition has errors: \n"); + for (String message : parseResult.getMessages()) { + errorMessage.append(message).append(LINE_SEPARATOR); + } + throw new BallerinaOpenApiException(errorMessage.toString()); + } + return parseResult.getOpenAPI(); + } + + /** + * 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/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CodeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CodeGenerator.java deleted file mode 100644 index 7e5efeb36..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/CodeGenerator.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.openapi.cmd; - -import io.ballerina.compiler.api.SemanticModel; -import io.ballerina.compiler.api.symbols.Symbol; -import io.ballerina.compiler.api.symbols.SymbolKind; -import io.ballerina.compiler.syntax.tree.ChildNodeEntry; -import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; -import io.ballerina.compiler.syntax.tree.ModulePartNode; -import io.ballerina.compiler.syntax.tree.NodeList; -import io.ballerina.compiler.syntax.tree.SyntaxKind; -import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; -import io.ballerina.openapi.cmd.model.GenSrcFile; -import io.ballerina.openapi.converter.utils.CodegenUtils; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaClientGenerator; -import io.ballerina.openapi.generators.client.BallerinaTestGenerator; -import io.ballerina.openapi.generators.client.BallerinaUtilGenerator; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; -import io.ballerina.openapi.generators.service.BallerinaServiceGenerator; -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.Location; -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.media.Schema; -import org.apache.commons.io.FileUtils; -import org.ballerinalang.formatter.core.Formatter; -import org.ballerinalang.formatter.core.FormatterException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -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.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static io.ballerina.openapi.generators.GeneratorConstants.BALLERINA_TOML; -import static io.ballerina.openapi.generators.GeneratorConstants.BALLERINA_TOML_CONTENT; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.DEFAULT_CLIENT_PKG; -import static io.ballerina.openapi.generators.GeneratorConstants.DEFAULT_MOCK_PKG; -import static io.ballerina.openapi.generators.GeneratorConstants.DOUBLE_LINE_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.GET; -import static io.ballerina.openapi.generators.GeneratorConstants.GenType.GEN_CLIENT; -import static io.ballerina.openapi.generators.GeneratorConstants.GenType.GEN_SERVICE; -import static io.ballerina.openapi.generators.GeneratorConstants.HEAD; -import static io.ballerina.openapi.generators.GeneratorConstants.IDENTIFIER; -import static io.ballerina.openapi.generators.GeneratorConstants.LINE_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.OAS_PATH_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.SERVICE_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.TEST_DIR; -import static io.ballerina.openapi.generators.GeneratorConstants.TEST_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.TYPE_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.TYPE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.UNTITLED_SERVICE; -import static io.ballerina.openapi.generators.GeneratorConstants.UTIL_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.setGeneratedFileName; - -/** - * This class generates Ballerina Services/Clients for a provided OAS definition. - */ -public class CodeGenerator { - private String srcPackage; - private String licenseHeader = ""; - private boolean includeTestFiles; - - private static final PrintStream outStream = System.err; - private static final Logger LOGGER = LoggerFactory.getLogger(BallerinaUtilGenerator.class); - - /** - * Generates ballerina source for provided Open API Definition in {@code definitionPath}. - * Generated source will be written to a ballerina module at {@code outPath} - *

Method can be user for generating Ballerina mock services and clients

- */ - - public void generateBothFiles(GeneratorConstants.GenType type, String definitionPath, String serviceName, - String outPath, Filter filter, boolean nullable, boolean isResource) - throws IOException, BallerinaOpenApiException, FormatterException { - Path srcPath = Paths.get(outPath); - Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); - - List sourceFiles = new ArrayList<>(); - Path openAPIPath = Path.of(definitionPath); - // Normalize OpenAPI definition, in the client generation we suppose to terminate code generation when the - // absence of the operationId in operation. Therefor we enable client flag true as default code generation. - // if resource is enabled, we avoid checking operationId. - OpenAPI openAPIDef = normalizeOpenAPI(openAPIPath, !isResource); - - // Generate service - String concatTitle = serviceName.toLowerCase(Locale.ENGLISH); - String srcFile = concatTitle + "_service.bal"; - BallerinaServiceGenerator serviceGenerator = new BallerinaServiceGenerator(openAPIDef, filter); - String serviceContent = Formatter.format - (serviceGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, srcFile, serviceContent)); - - // Generate client. - // Generate ballerina client remote. - BallerinaClientGenerator clientGenerator = new BallerinaClientGenerator(openAPIDef, filter, nullable, - isResource); - String clientContent = Formatter.format(clientGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CLIENT_FILE_NAME, clientContent)); - String utilContent = Formatter.format(clientGenerator - .getBallerinaUtilGenerator() - .generateUtilSyntaxTree()).toString(); - if (!utilContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, UTIL_FILE_NAME, utilContent)); - } - - // Generate ballerina types. - // Generate ballerina records to represent schemas. - BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPIDef, nullable); - - //Update type definition list - List typeInclusionRecords = serviceGenerator.getTypeInclusionRecords(); - List typeDefinitionNodeList = clientGenerator.getTypeDefinitionNodeList(); - List externalTypeDefNodes = new ArrayList<>(); - externalTypeDefNodes.addAll(typeInclusionRecords); - externalTypeDefNodes.addAll(typeDefinitionNodeList); - - ballerinaSchemaGenerator.setTypeDefinitionNodeList(externalTypeDefNodes); - SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); - String schemaContent = Formatter.format(schemaSyntaxTree).toString(); - - if (filter.getTags().size() > 0) { - // Remove unused records and enums when generating the client by the tags given. - schemaContent = modifySchemaContent(schemaSyntaxTree, clientContent, schemaContent, serviceContent); - } - if (!schemaContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, - schemaContent)); - } - - // Generate test boilerplate code for test cases - if (this.includeTestFiles) { - BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(clientGenerator); - String testContent = Formatter.format(ballerinaTestGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TEST_FILE_NAME, testContent)); - - String configContent = ballerinaTestGenerator.getConfigTomlFile(); - if (!configContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, - CONFIG_FILE_NAME, configContent)); - } - } - - List newGenFiles = sourceFiles.stream() - .filter(distinctByKey(GenSrcFile::getFileName)) - .collect(Collectors.toList()); - - writeGeneratedSources(newGenFiles, srcPath, implPath, type); - } - - public static Predicate distinctByKey( - Function keyExtractor) { - Map seen = new ConcurrentHashMap<>(); - return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; - } - - /** - * Generates ballerina source for provided Open API Definition in {@code definitionPath}. - * Generated source will be written to a ballerina module at {@code outPath} - * Method can be user for generating Ballerina clients. - * - * @param definitionPath Input Open Api Definition file path - * @param outPath Destination file path to save generated source files. If not provided - * {@code definitionPath} will be used as the default destination path - * @param filter For take the tags and operation option values - * @param nullable Enable nullable option for make record field optional - * @throws IOException when file operations fail - * @throws BallerinaOpenApiException when code generator fails - */ - public void generateClient(String definitionPath, String outPath, Filter filter, boolean nullable, - boolean isResource) - throws IOException, BallerinaOpenApiException, FormatterException { - Path srcPath = Paths.get(outPath); - Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); - List genFiles = generateClientFiles(Paths.get(definitionPath), filter, nullable, isResource); - writeGeneratedSources(genFiles, srcPath, implPath, GEN_CLIENT); - } - - /** - * Generates ballerina source for provided Open API Definition in {@code definitionPath}. - * Generated source will be written to a ballerina module at {@code outPath} - * Method can be user for generating Ballerina clients. - * - * @param definitionPath Input Open Api Definition file path - * @param serviceName service name for the generated service - * @param outPath Destination file path to save generated source files. If not provided - * {@code definitionPath} will be used as the default destination path - * @throws IOException when file operations fail - * @throws BallerinaOpenApiException when code generator fails - */ - public void generateService(String definitionPath, String serviceName, String outPath, Filter filter, - boolean nullable) - throws IOException, BallerinaOpenApiException, FormatterException { - Path srcPath = Paths.get(outPath); - Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); - List genFiles = generateBallerinaService(Paths.get(definitionPath), serviceName, filter, nullable); - writeGeneratedSources(genFiles, srcPath, implPath, GEN_SERVICE); - } - - private void writeGeneratedSources(List sources, Path srcPath, Path implPath, - GeneratorConstants.GenType type) - throws IOException { - // Remove old generated file with same name - List listFiles = new ArrayList<>(); - 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 = implPath.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 + OAS_PATH_SEPARATOR + TEST_DIR)); - filePath = Paths.get(srcPath.resolve(TEST_DIR + OAS_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); - } - } - - //This will print the generated files to the console - if (type.equals(GEN_SERVICE)) { - outStream.println("Service generated successfully and the OpenAPI contract is copied to path " + srcPath - + "."); - } else if (type.equals(GEN_CLIENT)) { - 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. - * - * @return generated source files as a list of {@link GenSrcFile} - * @throws IOException when code generation with specified templates fails - */ - private List generateClientFiles(Path openAPI, Filter filter, boolean nullable, boolean isResource) - throws IOException, BallerinaOpenApiException, FormatterException { - if (srcPackage == null || srcPackage.isEmpty()) { - srcPackage = DEFAULT_CLIENT_PKG; - } - List sourceFiles = new ArrayList<>(); - // Normalize OpenAPI definition - OpenAPI openAPIDef = normalizeOpenAPI(openAPI, !isResource); - // Generate ballerina service and resources. - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPIDef, filter, nullable - , isResource); - String mainContent = Formatter.format(ballerinaClientGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CLIENT_FILE_NAME, mainContent)); - String utilContent = Formatter.format( - ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree()).toString(); - if (!utilContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, UTIL_FILE_NAME, utilContent)); - } - - // Generate ballerina records to represent schemas. - BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPIDef, nullable); - ballerinaSchemaGenerator.setTypeDefinitionNodeList(ballerinaClientGenerator.getTypeDefinitionNodeList()); - SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); - String schemaContent = Formatter.format(schemaSyntaxTree).toString(); - if (filter.getTags().size() > 0) { - // Remove unused records and enums when generating the client by the tags given. - schemaContent = modifySchemaContent(schemaSyntaxTree, mainContent, schemaContent, null); - } - if (!schemaContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, - schemaContent)); - } - - // Generate test boilerplate code for test cases - if (this.includeTestFiles) { - BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(ballerinaClientGenerator); - String testContent = Formatter.format(ballerinaTestGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TEST_FILE_NAME, testContent)); - - String configContent = ballerinaTestGenerator.getConfigTomlFile(); - if (!configContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, - GeneratorConstants.CONFIG_FILE_NAME, configContent)); - } - } - - return sourceFiles; - } - - private String modifySchemaContent(SyntaxTree schemaSyntaxTree, String clientContent, String schemaContent, - String serviceContent) throws IOException, FormatterException { - Map tempSourceFiles = new HashMap<>(); - tempSourceFiles.put(CLIENT_FILE_NAME, clientContent); - tempSourceFiles.put(TYPE_FILE_NAME, schemaContent); - if (serviceContent != null) { - tempSourceFiles.put(SERVICE_FILE_NAME, schemaContent); - } - List unusedTypeDefinitionNameList = getUnusedTypeDefinitionNameList(tempSourceFiles); - while (unusedTypeDefinitionNameList.size() > 0) { - ModulePartNode modulePartNode = schemaSyntaxTree.rootNode(); - NodeList members = modulePartNode.members(); - List unusedTypeDefinitionNodeList = new ArrayList<>(); - for (ModuleMemberDeclarationNode node : members) { - if (node.kind().equals(SyntaxKind.TYPE_DEFINITION)) { - for (ChildNodeEntry childNodeEntry : node.childEntries()) { - if (childNodeEntry.name().equals(TYPE_NAME)) { - if (unusedTypeDefinitionNameList.contains(childNodeEntry.node().get().toString())) { - unusedTypeDefinitionNodeList.add(node); - } - } - } - } else if (node.kind().equals(SyntaxKind.ENUM_DECLARATION)) { - for (ChildNodeEntry childNodeEntry : node.childEntries()) { - if (childNodeEntry.name().equals(IDENTIFIER)) { - if (unusedTypeDefinitionNameList.contains(childNodeEntry.node().get().toString())) { - unusedTypeDefinitionNodeList.add(node); - } - } - } - } - } - NodeList modifiedMembers = members.removeAll - (unusedTypeDefinitionNodeList); - ModulePartNode modiedModulePartNode = modulePartNode.modify(modulePartNode.imports(), - modifiedMembers, modulePartNode.eofToken()); - schemaSyntaxTree = schemaSyntaxTree.modifyWith(modiedModulePartNode); - schemaContent = Formatter.format(schemaSyntaxTree).toString(); - tempSourceFiles.put(TYPE_FILE_NAME, schemaContent); - unusedTypeDefinitionNameList = getUnusedTypeDefinitionNameList(tempSourceFiles); - } - return schemaContent; - } - - private List getUnusedTypeDefinitionNameList(Map srcFiles) throws IOException { - List unusedTypeDefinitionNameList = new ArrayList<>(); - Path tmpDir = Files.createTempDirectory(".openapi-tmp" + System.nanoTime()); - writeFilesTemp(srcFiles, tmpDir); - if (Files.exists(tmpDir.resolve(CLIENT_FILE_NAME)) && Files.exists(tmpDir.resolve(TYPE_FILE_NAME)) && - Files.exists(tmpDir.resolve(BALLERINA_TOML))) { - SemanticModel semanticModel = this.getSemanticModel(tmpDir.resolve(CLIENT_FILE_NAME)); - List symbols = semanticModel.moduleSymbols(); - for (Symbol symbol : symbols) { - if (symbol.kind().equals(SymbolKind.TYPE_DEFINITION) || symbol.kind().equals(SymbolKind.ENUM)) { - List references = semanticModel.references(symbol); - if (references.size() == 1) { - unusedTypeDefinitionNameList.add(symbol.getName().get()); - } - } - } - } - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - try { - FileUtils.deleteDirectory(tmpDir.toFile()); - } catch (IOException ex) { - LOGGER.error("Unable to delete the temporary directory : " + tmpDir, ex); - } - })); - return unusedTypeDefinitionNameList; - } - - private void writeFilesTemp(Map srcFiles, Path tmpDir) throws IOException { - srcFiles.put(BALLERINA_TOML, BALLERINA_TOML_CONTENT); - PrintWriter writer = null; - for (Map.Entry entry : srcFiles.entrySet()) { - String key = entry.getKey(); - Path filePath = tmpDir.resolve(key); - try { - writer = new PrintWriter(filePath.toString(), "UTF-8"); - writer.print(entry.getValue()); - } finally { - if (writer != null) { - writer.close(); - } - } - } - } - - private SemanticModel getSemanticModel(Path clientPath) throws ProjectException { - // Load project instance for single ballerina file - try { - Project project = ProjectLoader.loadProject(clientPath); - Package packageName = project.currentPackage(); - DocumentId docId; - - if (project.kind().equals(ProjectKind.BUILD_PROJECT)) { - docId = project.documentId(clientPath); - } 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()); - } catch (ProjectException e) { - throw new ProjectException(e.getMessage()); - } - } - - - public List generateBallerinaService(Path openAPI, String serviceName, - Filter filter, boolean nullable) - throws IOException, FormatterException, BallerinaOpenApiException { - if (srcPackage == null || srcPackage.isEmpty()) { - srcPackage = DEFAULT_MOCK_PKG; - } - OpenAPI openAPIDef = normalizeOpenAPI(openAPI, false); - if (openAPIDef.getInfo() == null) { - throw new BallerinaOpenApiException("Info section of the definition file cannot be empty/null: " + - openAPI); - } - - if (openAPIDef.getInfo().getTitle().isBlank() && (serviceName == null || serviceName.isBlank())) { - openAPIDef.getInfo().setTitle(UNTITLED_SERVICE); - } else { - openAPIDef.getInfo().setTitle(serviceName); - } - - List sourceFiles = new ArrayList<>(); - String concatTitle = serviceName == null ? - openAPIDef.getInfo().getTitle().toLowerCase(Locale.ENGLISH) : - serviceName.toLowerCase(Locale.ENGLISH); - String srcFile = concatTitle + "_service.bal"; - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPIDef, filter); - String mainContent = Formatter.format - (ballerinaServiceGenerator.generateSyntaxTree()).toString(); - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, srcFile, mainContent)); - - BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPIDef, nullable); - ballerinaSchemaGenerator.setTypeDefinitionNodeList(ballerinaServiceGenerator.getTypeInclusionRecords()); - String schemaContent = Formatter.format( - ballerinaSchemaGenerator.generateSyntaxTree()).toString(); - if (!schemaContent.isBlank()) { - sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TYPE_FILE_NAME, - schemaContent)); - } - return sourceFiles; - } - - /** - * Normalized OpenAPI specification with adding proper naming to schema. - * - * @param openAPIPath - openAPI file path - * @return - openAPI specification - * @throws IOException - * @throws BallerinaOpenApiException - */ - public OpenAPI normalizeOpenAPI(Path openAPIPath, boolean isClient) throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(openAPIPath); - io.swagger.v3.oas.models.Paths openAPIPaths = openAPI.getPaths(); - if (isClient) { - validateOperationIds(openAPIPaths.entrySet()); - } - validateRequestBody(openAPIPaths.entrySet()); - - if (openAPI.getComponents() != null) { - // Refactor schema name with valid name - Components components = openAPI.getComponents(); - Map componentsSchemas = components.getSchemas(); - if (componentsSchemas != null) { - Map refacSchema = new HashMap<>(); - for (Map.Entry schemaEntry : componentsSchemas.entrySet()) { - String name = getValidName(schemaEntry.getKey(), true); - refacSchema.put(name, schemaEntry.getValue()); - } - openAPI.getComponents().setSchemas(refacSchema); - } - } - return openAPI; - } - - /** - * Check whether an operationId has been defined in each path. If given rename the operationId to accepted format. - * -- ex: GetPetName -> getPetName - * - * @param paths List of paths given in the OpenAPI definition - * @throws BallerinaOpenApiException When operationId is missing in any path - */ - private void validateOperationIds(Set> paths) throws BallerinaOpenApiException { - List errorList = new ArrayList<>(); - for (Map.Entry entry : paths) { - for (Map.Entry operation : - entry.getValue().readOperationsMap().entrySet()) { - if (operation.getValue().getOperationId() != null) { - String operationId = getValidName(operation.getValue().getOperationId(), false); - operation.getValue().setOperationId(operationId); - } else { - errorList.add(String.format("OperationId is missing in the resource path: %s(%s)", entry.getKey(), - operation.getKey())); - } - } - } - if (!errorList.isEmpty()) { - throw new BallerinaOpenApiException( - "OpenAPI definition has errors: " + - DOUBLE_LINE_SEPARATOR + String.join(LINE_SEPARATOR, errorList)); - } - } - - /** - * Validate if requestBody found in GET/DELETE/HEAD operation. - * - * @param paths - List of paths given in the OpenAPI definition - * @throws BallerinaOpenApiException - If requestBody found in GET/DELETE/HEAD operation - */ - private void validateRequestBody(Set> paths) throws BallerinaOpenApiException { - List errorList = new ArrayList<>(); - for (Map.Entry entry : paths) { - if (!entry.getValue().readOperationsMap().isEmpty()) { - for (Map.Entry operation : entry.getValue().readOperationsMap() - .entrySet()) { - String method = operation.getKey().name().trim().toLowerCase(Locale.ENGLISH); - boolean isRequestBodyInvalid = method.equals(GET) || method.equals(HEAD); - if (isRequestBodyInvalid && operation.getValue().getRequestBody() != null) { - errorList.add(method.toUpperCase(Locale.ENGLISH) + " operation cannot have a requestBody. " - + "Error at operationId: " + operation.getValue().getOperationId()); - } - } - } - } - - if (!errorList.isEmpty()) { - StringBuilder errorMessage = new StringBuilder("OpenAPI definition has errors: " + DOUBLE_LINE_SEPARATOR); - for (String message : errorList) { - errorMessage.append(message).append(LINE_SEPARATOR); - } - throw new BallerinaOpenApiException(errorMessage.toString()); - } - } - - /** - * Set the content of license header. - * - * @param licenseHeader license header value received from command line. - */ - public void setLicenseHeader(String licenseHeader) { - this.licenseHeader = licenseHeader; - } - - /** - * set whether to add test files or not. - * - * @param includeTestFiles value received from command line by "--with tests" - */ - public void setIncludeTestFiles(boolean includeTestFiles) { - this.includeTestFiles = includeTestFiles; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiMesseges.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/ErrorMessages.java similarity index 69% rename from openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiMesseges.java rename to openapi-cli/src/main/java/io/ballerina/openapi/cmd/ErrorMessages.java index ea38a96e9..c039e49d4 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiMesseges.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/ErrorMessages.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 @@ -15,19 +15,22 @@ * specific language governing permissions and limitations * under the License. */ + package io.ballerina.openapi.cmd; /** * This class contains the messages constants required for OpenApi tool. + * + * @since 1.3.0 */ -public class OpenApiMesseges { +public class ErrorMessages { - public static final String OPENAPI_CLIENT_EXCEPTION = "Error occurred when generating client for OpenAPI contract"; + public static final String CLIENT_GENERATION_FAILED = "Error occurred when generating client for OpenAPI contract"; - public static final String MESSAGE_FOR_MISSING_INPUT = "An OpenAPI definition file is required to generate the " + + public static final String MISSING_CONTRACT_PATH = "An OpenAPI definition path is required to generate the " + "service. \ne.g: bal openapi --input or "; - private OpenApiMesseges() { + private ErrorMessages() { throw new AssertionError(); } } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/Filter.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/Filter.java deleted file mode 100644 index 9e4e87db4..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/Filter.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.openapi.cmd; - -import java.util.ArrayList; -import java.util.List; - -/** - * This model use for storing the filter tags and operations details. - */ -public class Filter { - private List tags = new ArrayList<>(); - private List operations = new ArrayList<>(); - - public Filter(List tags, List operations) { - this.tags = tags; - this.operations = operations; - } - - public List getTags() { - return tags; - } - - public List getOperations() { - return operations; - } - - public void setOperations(List operations) { - this.operations = operations; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/openapi/OpenApiConverter.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OASContractGenerator.java similarity index 75% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/openapi/OpenApiConverter.java rename to openapi-cli/src/main/java/io/ballerina/openapi/cmd/OASContractGenerator.java index 2b663e3de..349e43b53 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/openapi/OpenApiConverter.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OASContractGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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. + * 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.openapi.generators.openapi; +package io.ballerina.openapi.cmd; import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.syntax.tree.SyntaxTree; @@ -26,11 +26,11 @@ import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.CodegenUtils; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; 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; @@ -49,9 +49,11 @@ /** * OpenApi related utility classes. + * + * @since 1.3.0 */ -public class OpenApiConverter { +public class OASContractGenerator { private SyntaxTree syntaxTree; private SemanticModel semanticModel; private Project project; @@ -61,7 +63,7 @@ public class OpenApiConverter { /** * Initialize constructor. */ - public OpenApiConverter() { + public OASContractGenerator() { } @@ -80,7 +82,9 @@ public void generateOAS3DefinitionsAllService(Path servicePath, Path outPath, St Boolean needJson) { // Load project instance for single ballerina file project = ProjectLoader.loadProject(servicePath); - Package packageName = project.currentPackage(); + DiagnosticResult diagnosticsFromCodeGenAndModify = project.currentPackage().runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); DocumentId docId; Document doc; if (project.kind().equals(ProjectKind.BUILD_PROJECT)) { @@ -89,7 +93,7 @@ public void generateOAS3DefinitionsAllService(Path servicePath, Path outPath, St doc = project.currentPackage().module(moduleId).document(docId); } else { // Take module instance for traversing the syntax tree - Module currentModule = packageName.getDefaultModule(); + Module currentModule = project.currentPackage().getDefaultModule(); Iterator documentIterator = currentModule.documentIds().iterator(); docId = documentIterator.next(); @@ -100,15 +104,15 @@ public void generateOAS3DefinitionsAllService(Path servicePath, Path outPath, St syntaxTree = doc.syntaxTree(); PackageCompilation compilation = project.currentPackage().getCompilation(); - boolean hasErrors = compilation.diagnosticResult() + boolean hasCompilationErrors = compilation.diagnosticResult() .diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed return; } semanticModel = compilation.getSemanticModel(docId.moduleId()); - List openAPIDefinitions = ServiceToOpenAPIConverterUtils.generateOAS3Definition(syntaxTree, + List openAPIDefinitions = ServiceToOpenAPIConverterUtils.generateOAS3Definition(project, syntaxTree, semanticModel, serviceName, needJson, inputPath); if (!openAPIDefinitions.isEmpty()) { @@ -138,11 +142,16 @@ public void generateOAS3DefinitionsAllService(Path servicePath, Path outPath, St if (fileNames.isEmpty()) { return; } - outStream.println("OpenAPI definition(s) generated successfully and copy to :"); + outStream.println("OpenAPI definition(s) generated successfully and copied to :"); Iterator iterator = fileNames.iterator(); while (iterator.hasNext()) { outStream.println("-- " + iterator.next()); } + } else { + DiagnosticMessages message = DiagnosticMessages.OAS_CONVERTOR_115; + ExceptionDiagnostic error = new ExceptionDiagnostic(message.getCode(), + message.getDescription(), null); + this.errors.add(error); } } } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenAPIDiagnostic.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenAPIDiagnostic.java index d5571cbfa..1db360b48 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenAPIDiagnostic.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenAPIDiagnostic.java @@ -26,6 +26,7 @@ import java.text.MessageFormat; import java.util.List; + /** * Represents a {@code Diagnostic} related to openapi command. * @@ -62,7 +63,7 @@ public List> properties() { } @Override - public String toString() { + 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/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiCmd.java b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiCmd.java index aa4e65159..dee9c84e9 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiCmd.java +++ b/openapi-cli/src/main/java/io/ballerina/openapi/cmd/OpenApiCmd.java @@ -22,15 +22,18 @@ import io.ballerina.openapi.converter.diagnostic.ExceptionDiagnostic; import io.ballerina.openapi.converter.diagnostic.IncompatibleResourceDiagnostic; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.openapi.OpenApiConverter; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.model.Filter; 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; @@ -39,14 +42,15 @@ import java.util.List; import java.util.stream.Collectors; +import static io.ballerina.openapi.cmd.CmdConstants.BAL_EXTENSION; +import static io.ballerina.openapi.cmd.CmdConstants.CLIENT; +import static io.ballerina.openapi.cmd.CmdConstants.JSON_EXTENSION; import static io.ballerina.openapi.cmd.CmdConstants.REMOTE; +import static io.ballerina.openapi.cmd.CmdConstants.RESOURCE; import static io.ballerina.openapi.cmd.CmdConstants.SERVICE; -import static io.ballerina.openapi.generators.GeneratorConstants.BAL_EXTENSION; -import static io.ballerina.openapi.generators.GeneratorConstants.JSON_EXTENSION; -import static io.ballerina.openapi.generators.GeneratorConstants.RESOURCE; -import static io.ballerina.openapi.generators.GeneratorConstants.YAML_EXTENSION; -import static io.ballerina.openapi.generators.GeneratorConstants.YML_EXTENSION; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.cmd.CmdConstants.YAML_EXTENSION; +import static io.ballerina.openapi.cmd.CmdConstants.YML_EXTENSION; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; /** * Main class to implement "openapi" command for ballerina. Commands for Client Stub, Service file and OpenApi contract @@ -54,8 +58,7 @@ */ @CommandLine.Command( name = "openapi", - description = "Generates Ballerina service/client for OpenAPI contract and OpenAPI contract for Ballerina" + - "Service." + description = "Generate the Ballerina sources for a given OpenAPI definition and vice versa." ) public class OpenApiCmd implements BLauncherCmd { private static final String CMD_NAME = "openapi"; @@ -105,9 +108,16 @@ public class OpenApiCmd implements BLauncherCmd { private boolean includeTestFiles; @CommandLine.Option(names = {"--client-methods"}, hidden = true, description = "Generate the client methods" + - " with provided type . Only \"remote\"(default) and \"resource\" options are supported.") + " with provided type . Only \"resource\"(default) and \"remote\" options are supported.") private String generateClientMethods; + @CommandLine.Option(names = {"--with-service-type"}, hidden = true, description = "Generate service type") + private boolean generateServiceType; + + @CommandLine.Option(names = {"--without-data-binding"}, hidden = true, + description = "Generate service without data binding") + private boolean generateWithoutDataBinding; + @CommandLine.Parameters private List argList; @@ -138,7 +148,7 @@ public void execute() { if (inputPath) { //Check if an OpenApi definition is provided if (argList == null) { - outStream.println(OpenApiMesseges.MESSAGE_FOR_MISSING_INPUT); + outStream.println(ErrorMessages.MISSING_CONTRACT_PATH); exitError(this.exitWhenFinish); return; } @@ -169,14 +179,20 @@ public void execute() { exitError(this.exitWhenFinish); } // Add the resource flag enable - clientResourceMode = generateClientMethods != null && !generateClientMethods.isBlank() && - (generateClientMethods.equals(CmdConstants.RESOURCE)); + clientResourceMode = generateClientMethods == null || generateClientMethods.isBlank() || + (!generateClientMethods.equals(REMOTE)); - if (clientResourceMode && mode != null && mode.equals(SERVICE)) { + if (!clientResourceMode && mode != null && mode.equals(SERVICE)) { // Exit the code generation process outStream.println("'--client-methods' option is only available in client generation mode."); exitError(this.exitWhenFinish); } + + if (generateWithoutDataBinding && mode != null && mode.equals(CLIENT)) { + // Exit the code generation process + outStream.println("'--without-data-binding' option is only available in service generation mode."); + exitError(this.exitWhenFinish); + } try { openApiToBallerina(fileName, filter); } catch (IOException e) { @@ -192,7 +208,7 @@ public void execute() { } ballerinaToOpenApi(fileName); } else { - outStream.println(OpenApiMesseges.MESSAGE_FOR_MISSING_INPUT); + outStream.println(ErrorMessages.MISSING_CONTRACT_PATH); exitError(this.exitWhenFinish); } } else { @@ -225,7 +241,7 @@ private void ballerinaToOpenApi(String fileName) { } getTargetOutputPath(); // Check service name it is mandatory - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(balFilePath, targetOutputPath, service, generatedFileType); errors.addAll(openApiConverter.getErrors()); @@ -256,7 +272,7 @@ private void ballerinaToOpenApi(String fileName) { * @param fileName input resource file */ private void openApiToBallerina(String fileName, Filter filter) throws IOException { - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); generator.setLicenseHeader(this.setLicenseHeader()); generator.setIncludeTestFiles(this.includeTestFiles); final File openApiFile = new File(fileName); @@ -268,6 +284,10 @@ private void openApiToBallerina(String fileName, Filter filter) throws IOExcepti } getTargetOutputPath(); Path resourcePath = Paths.get(openApiFile.getCanonicalPath()); + if (nullable) { + outStream.println("WARNING: All the constraints in the OpenAPI contract will be ignored when generating" + + " the Ballerina client/service with the `--nullable` option"); + } if (mode != null) { switch (mode) { case "service": @@ -343,17 +363,17 @@ private String setLicenseHeader() { * @param resourcePath resource Path * @param resourceMode flag for client resource method generation */ - private void generatesClientFile(CodeGenerator generator, Path resourcePath, Filter filter, + private void generatesClientFile(BallerinaCodeGenerator generator, Path resourcePath, Filter filter, boolean resourceMode) { try { generator.generateClient(resourcePath.toString(), targetOutputPath.toString(), filter, nullable, resourceMode); - } catch (IOException | BallerinaOpenApiException | FormatterException e) { + } catch (IOException | FormatterException | BallerinaOpenApiException e) { if (e.getLocalizedMessage() != null) { outStream.println(e.getLocalizedMessage()); exitError(this.exitWhenFinish); } else { - outStream.println(OpenApiMesseges.OPENAPI_CLIENT_EXCEPTION); + outStream.println(ErrorMessages.CLIENT_GENERATION_FAILED); exitError(this.exitWhenFinish); } } @@ -365,13 +385,14 @@ private void generatesClientFile(CodeGenerator generator, Path resourcePath, Fi * @param serviceName service name uses for naming the generated file * @param resourcePath resource Path */ - private void generateServiceFile(CodeGenerator generator, String serviceName, Path resourcePath, Filter filter) { + private void generateServiceFile(BallerinaCodeGenerator generator, String serviceName, Path resourcePath, + Filter filter) { try { assert resourcePath != null; generator.generateService(resourcePath.toString(), serviceName, targetOutputPath.toString(), filter, - nullable); - } catch (IOException | BallerinaOpenApiException | FormatterException e) { + nullable, generateServiceType, generateWithoutDataBinding); + } catch (IOException | FormatterException | BallerinaOpenApiException e) { outStream.println("Error occurred when generating service for OpenAPI contract at " + argList.get(0) + ". " + e.getMessage() + "."); exitError(this.exitWhenFinish); @@ -384,13 +405,12 @@ private void generateServiceFile(CodeGenerator generator, String serviceName, Pa * @param fileName service name use for naming the files * @param resourcePath resource path */ - private void generateBothFiles(CodeGenerator generator, String fileName, Path resourcePath, Filter filter, - boolean generateClientResourceFunctions) { + private void generateBothFiles(BallerinaCodeGenerator generator, String fileName, Path resourcePath, + Filter filter, boolean generateClientResourceFunctions) { try { assert resourcePath != null; - generator.generateBothFiles(GeneratorConstants.GenType.GEN_BOTH, - resourcePath.toString(), fileName, targetOutputPath.toString(), filter, nullable, - generateClientResourceFunctions); + generator.generateClientAndService(resourcePath.toString(), fileName, targetOutputPath.toString(), filter, + nullable, generateClientResourceFunctions, generateServiceType, generateWithoutDataBinding); } catch (IOException | BallerinaOpenApiException | FormatterException e) { outStream.println("Error occurred when generating service for openAPI contract at " + argList.get(0) + "." + " " + e.getMessage() + "."); @@ -405,6 +425,16 @@ public String getName() { @Override public void printLongDesc(StringBuilder out) { + InputStream inputStream = ClassLoader.getSystemResourceAsStream("ballerina-openapi.help"); + try (InputStreamReader inputStreamREader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + BufferedReader br = new BufferedReader(inputStreamREader)) { + String content = br.readLine(); + out.append(content); + while ((content = br.readLine()) != null) { + out.append('\n').append(content); + } + } catch (IOException ignore) { + } } @Override diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/exception/BallerinaOpenApiException.java b/openapi-cli/src/main/java/io/ballerina/openapi/exception/BallerinaOpenApiException.java deleted file mode 100644 index 67de878f1..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/exception/BallerinaOpenApiException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.openapi.exception; - -/** - * Exception type definition for OpenAPI to Ballerina parsing related errors. - */ -public class BallerinaOpenApiException extends Exception { - public BallerinaOpenApiException(String message, Throwable e) { - super(message, e); - } - - public BallerinaOpenApiException(String message) { - super(message); - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorUtils.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorUtils.java deleted file mode 100644 index 3e6233f81..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorUtils.java +++ /dev/null @@ -1,579 +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.openapi.generators; - -import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; -import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; -import io.ballerina.compiler.syntax.tree.ExpressionNode; -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.Node; -import io.ballerina.compiler.syntax.tree.NodeFactory; -import io.ballerina.compiler.syntax.tree.NodeParser; -import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; -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.SpecificFieldNode; -import io.ballerina.compiler.syntax.tree.StatementNode; -import io.ballerina.compiler.syntax.tree.SyntaxInfo; -import io.ballerina.compiler.syntax.tree.SyntaxKind; -import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; -import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.ErrorMessages; -import io.ballerina.openapi.cmd.model.GenSrcFile; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.media.ObjectSchema; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.parameters.Parameter; -import io.swagger.v3.oas.models.servers.ServerVariable; -import io.swagger.v3.oas.models.servers.ServerVariables; -import io.swagger.v3.parser.OpenAPIV3Parser; -import io.swagger.v3.parser.core.models.ParseOptions; -import io.swagger.v3.parser.core.models.SwaggerParseResult; - -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.Matcher; -import java.util.regex.Pattern; - -import javax.ws.rs.core.MediaType; - -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.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.createCaptureBindingPatternNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createResourcePathParameterNode; -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.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_BRACKET_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.EQUAL_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACKET_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.SLASH_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_KEYWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.ANY_TYPE; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_PDF; -import static io.ballerina.openapi.generators.GeneratorConstants.BALLERINA; -import static io.ballerina.openapi.generators.GeneratorConstants.CLOSE_CURLY_BRACE; -import static io.ballerina.openapi.generators.GeneratorConstants.EXPLODE; -import static io.ballerina.openapi.generators.GeneratorConstants.IMAGE_PNG; -import static io.ballerina.openapi.generators.GeneratorConstants.LINE_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.OPEN_CURLY_BRACE; -import static io.ballerina.openapi.generators.GeneratorConstants.SLASH; -import static io.ballerina.openapi.generators.GeneratorConstants.SPECIAL_CHARACTERS_REGEX; -import static io.ballerina.openapi.generators.GeneratorConstants.SQUARE_BRACKETS; -import static io.ballerina.openapi.generators.GeneratorConstants.STRING; -import static io.ballerina.openapi.generators.GeneratorConstants.STYLE; - -/** - * 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(); - - 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); - } - - public static QualifiedNameReferenceNode getQualifiedNameReferenceNode(String modulePrefix, String identifier) { - Token modulePrefixToken = AbstractNodeFactory.createIdentifierToken(modulePrefix); - Token colon = AbstractNodeFactory.createIdentifierToken(":"); - IdentifierToken identifierToken = AbstractNodeFactory.createIdentifierToken(identifier, SINGLE_WS_MINUTIAE - , SINGLE_WS_MINUTIAE); - return NodeFactory.createQualifiedNameReferenceNode(modulePrefixToken, colon, identifierToken); - } - - /** - * Generated resource function relative path node list. - * @param path - resource path - * @param operation - resource operation - * @return - node lists - * @throws BallerinaOpenApiException - */ - public static List getRelativeResourcePath(String path, Operation operation) - throws BallerinaOpenApiException { - List functionRelativeResourcePath = new ArrayList<>(); - String[] pathNodes = path.split(SLASH); - if (pathNodes.length >= 2) { - for (String pathNode: pathNodes) { - if (pathNode.contains(OPEN_CURLY_BRACE)) { - String pathParam = pathNode; - pathParam = pathParam.substring(pathParam.indexOf(OPEN_CURLY_BRACE) + 1); - pathParam = pathParam.substring(0, pathParam.indexOf(CLOSE_CURLY_BRACE)); - pathParam = getValidName(pathParam, false); - - /** - * TODO -> `onCall/[string id]\.json` type of url won't support from syntax - * issue https://github.com/ballerina-platform/ballerina-spec/issues/1138 - *
resource function get onCall/[string id]\.json() returns string {}
-                     */
-                    if (operation.getParameters() != null) {
-                        extractPathParameterDetails(operation, functionRelativeResourcePath, pathNode, pathParam);
-                    }
-                } else if (!pathNode.isBlank()) {
-                    IdentifierToken idToken = createIdentifierToken(escapeIdentifier(pathNode.trim()));
-                    functionRelativeResourcePath.add(idToken);
-                    functionRelativeResourcePath.add(createToken(SLASH_TOKEN));
-                }
-            }
-            functionRelativeResourcePath.remove(functionRelativeResourcePath.size() - 1);
-        } else if (pathNodes.length == 0) {
-            IdentifierToken idToken = createIdentifierToken(".");
-            functionRelativeResourcePath.add(idToken);
-        } else {
-            IdentifierToken idToken = createIdentifierToken(pathNodes[1].trim());
-            functionRelativeResourcePath.add(idToken);
-        }
-        return functionRelativeResourcePath;
-    }
-
-    private static void extractPathParameterDetails(Operation operation, List functionRelativeResourcePath,
-                                                    String pathNode, String pathParam)
-            throws BallerinaOpenApiException {
-        // check whether path parameter segment has special character
-        String[] split = pathNode.split(CLOSE_CURLY_BRACE, 2);
-        Pattern pattern = Pattern.compile(SPECIAL_CHARACTERS_REGEX);
-        Matcher matcher = pattern.matcher(split[1]);
-        boolean hasSpecialCharacter = matcher.find();
-
-        for (Parameter parameter : operation.getParameters()) {
-            if (parameter.getIn() == null) {
-                break;
-            }
-            if (pathParam.trim().equals(getValidName(parameter.getName().trim(), false))
-                    && parameter.getIn().equals("path")) {
-
-                // TypeDescriptor
-                BuiltinSimpleNameReferenceNode builtSNRNode = createBuiltinSimpleNameReferenceNode(
-                        null,
-                        parameter.getSchema() == null ?
-                                createIdentifierToken(STRING) :
-                                createIdentifierToken(
-                                        convertOpenAPITypeToBallerina(parameter.getSchema().getType())));
-                IdentifierToken paramName = createIdentifierToken(
-                        hasSpecialCharacter ?
-                                getValidName(pathNode, false) :
-                                pathParam);
-                ResourcePathParameterNode resourcePathParameterNode =
-                        createResourcePathParameterNode(
-                                SyntaxKind.RESOURCE_PATH_SEGMENT_PARAM,
-                                createToken(OPEN_BRACKET_TOKEN),
-                                NodeFactory.createEmptyNodeList(),
-                                builtSNRNode,
-                                null,
-                                paramName,
-                                createToken(CLOSE_BRACKET_TOKEN));
-                functionRelativeResourcePath.add(resourcePathParameterNode);
-                functionRelativeResourcePath.add(createToken(SLASH_TOKEN));
-                break;
-            }
-        }
-    }
-
-    /**
-     * Method for convert openApi type to ballerina type.
-     * @param type  OpenApi parameter types
-     * @return ballerina type
-     */
-    public static String convertOpenAPITypeToBallerina(String type) throws BallerinaOpenApiException {
-        if (GeneratorConstants.TYPE_MAP.containsKey(type)) {
-            return GeneratorConstants.TYPE_MAP.get(type);
-        } else {
-            throw new BallerinaOpenApiException("Unsupported OAS 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));
-        }
-    }
-
-    /**
-     * 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 BallerinaOpenApiException - 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 BallerinaOpenApiException {
-        if (referenceVariable.startsWith("#") && referenceVariable.contains("/")) {
-            String[] refArray = referenceVariable.split("/");
-            return refArray[refArray.length - 1];
-        } else {
-            throw new BallerinaOpenApiException("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 OpenApi spec from given yaml file.
-     */
-    public static OpenAPI getOpenAPIFromOpenAPIV3Parser(Path definitionPath) throws
-            IOException, BallerinaOpenApiException {
-
-        Path contractPath = java.nio.file.Paths.get(definitionPath.toString());
-        if (!Files.exists(contractPath)) {
-            throw new BallerinaOpenApiException(ErrorMessages.invalidFilePath(definitionPath.toString()));
-        }
-        if (!(definitionPath.toString().endsWith(".yaml") || definitionPath.toString().endsWith(".json") ||
-                definitionPath.toString().endsWith(".yml"))) {
-            throw new BallerinaOpenApiException(ErrorMessages.invalidFileType());
-        }
-        String openAPIFileContent = Files.readString(definitionPath);
-        ParseOptions parseOptions = new ParseOptions();
-        parseOptions.setResolve(true);
-        parseOptions.setFlatten(true);
-        SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(openAPIFileContent, null, parseOptions);
-        if (!parseResult.getMessages().isEmpty()) {
-            StringBuilder errorMessage = new StringBuilder("OpenAPI definition has errors: \n\n");
-            for (String message: parseResult.getMessages()) {
-                errorMessage.append(message).append(LINE_SEPARATOR);
-            }
-            throw new BallerinaOpenApiException(errorMessage.toString());
-        }
-        return parseResult.getOpenAPI();
-    }
-
-
-    /**
-     * Generate BallerinaMediaType for all the mediaTypes.
-     */
-    public static String getBallerinaMediaType(String mediaType) {
-        switch (mediaType) {
-            case MediaType.APPLICATION_JSON:
-                return SyntaxKind.JSON_KEYWORD.stringValue();
-            case MediaType.APPLICATION_XML:
-                return SyntaxKind.XML_KEYWORD.stringValue();
-            case MediaType.APPLICATION_FORM_URLENCODED:
-            case MediaType.TEXT_HTML:
-            case MediaType.TEXT_PLAIN:
-                return STRING_KEYWORD.stringValue();
-            case IMAGE_PNG:
-            case MediaType.APPLICATION_OCTET_STREAM:
-            case APPLICATION_PDF:
-            case ANY_TYPE:
-                return SyntaxKind.BYTE_KEYWORD.stringValue() + SQUARE_BRACKETS;
-            default:
-                return SyntaxKind.JSON_KEYWORD.stringValue();
-            // TODO: fill other types
-        }
-    }
-
-    /*
-     * Generate variableDeclarationNode.
-     */
-    public static VariableDeclarationNode getSimpleStatement(String responseType, String variable,
-                                                             String initializer) {
-        SimpleNameReferenceNode resTypeBind = createSimpleNameReferenceNode(createIdentifierToken(responseType));
-        CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode(createIdentifierToken(variable));
-        TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(resTypeBind, bindingPattern);
-        SimpleNameReferenceNode init = createSimpleNameReferenceNode(createIdentifierToken(initializer));
-
-        return createVariableDeclarationNode(createEmptyNodeList(), null, typedBindingPatternNode,
-                createToken(EQUAL_TOKEN), init, createToken(SEMICOLON_TOKEN));
-    }
-
-    /*
-     * 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, ServerVariables 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]);
-    }
-
-    /**
-     * Create each item of the encoding map.
-     *
-     * @param filedOfMap    Includes all the items in the encoding map
-     * @param style         Defines how multiple values are delimited and explode
-     * @param explode       Specifies whether arrays and objects should generate separate parameters
-     * @param key           Key of the item in the map
-     */
-    public static void createEncodingMap(List filedOfMap, String style, Boolean explode, String key) {
-        IdentifierToken fieldName = createIdentifierToken('"' + key + '"');
-        Token colon = createToken(COLON_TOKEN);
-        SpecificFieldNode styleField = createSpecificFieldNode(null,
-                createIdentifierToken(STYLE), createToken(COLON_TOKEN),
-                createRequiredExpressionNode(createIdentifierToken(style.toUpperCase(Locale.ROOT))));
-        SpecificFieldNode explodeField = createSpecificFieldNode(null,
-                createIdentifierToken(EXPLODE), createToken(COLON_TOKEN),
-                createRequiredExpressionNode(createIdentifierToken(explode.toString())));
-        ExpressionNode expressionNode = createMappingConstructorExpressionNode(
-                createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(styleField, createToken(COMMA_TOKEN),
-                        explodeField),
-                createToken(CLOSE_BRACE_TOKEN));
-        SpecificFieldNode specificFieldNode = createSpecificFieldNode(null,
-                fieldName, colon, expressionNode);
-        filedOfMap.add(specificFieldNode);
-        filedOfMap.add(createToken(COMMA_TOKEN));
-    }
-
-    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_CURLY_BRACE) &&
-                    pattern.matcher(subPath.split(CLOSE_CURLY_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_CURLY_BRACE) && - pattern.matcher(subPath.split(CLOSE_CURLY_BRACE, 2)[1]).find()) { - String pathParam = subPath; - pathParam = pathParam.substring(pathParam.indexOf(OPEN_CURLY_BRACE) + 1); - pathParam = pathParam.substring(0, pathParam.indexOf(CLOSE_CURLY_BRACE)); - pathParam = getValidName(pathParam, false); - - String[] subPathSplit = subPath.split(CLOSE_CURLY_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 value) { - if (value instanceof ObjectSchema && value.getProperties() != null) { - boolean constraintExists = value.getProperties().values().stream() - .anyMatch(GeneratorUtils::isConstraintExists); - if (constraintExists) { - return true; - } - } - - return isConstraintExists(value); - } - - private static boolean isConstraintExists(Schema 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; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java deleted file mode 100644 index 554303530..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java +++ /dev/null @@ -1,121 +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.openapi.generators.schema.ballerinatypegenerators; - -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.Token; -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.TypeReferenceNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.Schema; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.ASTERISK_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_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; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; - -/** - * Generate TypeDefinitionNode and TypeDescriptorNode for allOf schemas. - * -- ex: - * Sample OpenAPI : - *
- *    schemas:
- *     Dog:
- *       allOf:
- *       - $ref: "#/components/schemas/Pet"
- *       - type: object
- *         properties:
- *           bark:
- *             type: boolean
- *  
- * Generated Ballerina type for the allOf schema `Dog` : - *
- *  public type Dog record {
- *      *Pet;
- *      boolean bark?;
- *  };
- * 
- * - * @since 2.0.0 - */ -public class AllOfRecordTypeGenerator extends RecordTypeGenerator { - public AllOfRecordTypeGenerator(Schema schema, String typeName) { - super(schema, typeName); - } - - /** - * Generate TypeDescriptorNode for allOf schemas. - */ - @Override - public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - assert schema instanceof ComposedSchema; - ComposedSchema composedSchema = (ComposedSchema) schema; - List allOfSchemas = composedSchema.getAllOf(); - if (allOfSchemas.size() == 1 && allOfSchemas.get(0).get$ref() != null) { - ReferencedTypeGenerator referencedTypeGenerator = new ReferencedTypeGenerator(allOfSchemas.get(0), - typeName); - return referencedTypeGenerator.generateTypeDescriptorNode(); - } else { - List recordFieldList = generateAllOfRecordFields(allOfSchemas); - NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList); - return NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), - createToken(OPEN_BRACE_TOKEN), fieldNodes, null, - createToken(CLOSE_BRACE_TOKEN)); - } - } - - private List generateAllOfRecordFields(List allOfSchemas) throws BallerinaOpenApiException { - List recordFieldList = new ArrayList<>(); - for (Schema allOfSchema : allOfSchemas) { - if (allOfSchema.get$ref() != null) { - Token typeRef = AbstractNodeFactory.createIdentifierToken(getValidName( - extractReferenceType(allOfSchema.get$ref()), true)); - TypeReferenceNode recordField = NodeFactory.createTypeReferenceNode(createToken(ASTERISK_TOKEN), - typeRef, createToken(SEMICOLON_TOKEN)); - recordFieldList.add(recordField); - } else if (allOfSchema.getProperties() != null) { - Map properties = allOfSchema.getProperties(); - List required = allOfSchema.getRequired(); - recordFieldList.addAll(addRecordFields(required, properties.entrySet(), typeName)); - } else if (allOfSchema instanceof ComposedSchema) { - ComposedSchema nestedComposedSchema = (ComposedSchema) 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 BallerinaOpenApiException( - "Unsupported nested OneOf or AnyOf schema is found inside a AllOf schema."); - } - } - } - return recordFieldList; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java deleted file mode 100644 index 1015232b2..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java +++ /dev/null @@ -1,138 +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.openapi.generators.schema.ballerinatypegenerators; - -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.TypeDefinitionNode; -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.swagger.v3.oas.models.media.Schema; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; -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.CLOSE_BRACE_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.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.schema.TypeGeneratorUtils.getFieldApiDocs; -import static io.ballerina.openapi.generators.schema.TypeGeneratorUtils.getTypeGenerator; -import static io.ballerina.openapi.generators.schema.TypeGeneratorUtils.updateRecordFieldList; - -/** - * Generate TypeDefinitionNode and TypeDescriptorNode for object type schema. - * -- ex: - * Sample OpenAPI : - *
- *      components:
- *          schemas:
- *              Pet:
- *                  required:
- *                      - id
- *                      - name
- *                  properties:
- *                      id:
- *                          type: integer
- *                          format: int64
- *                      name:
- *                          type: string
- *                      tag:
- *                          type: string
- *                      type:
- *                          type: string
- *  
- * Generated Ballerina type for the schema `Pet` : - *
- * public type Pet record {
- *      int id;
- *      string name;
- *      string tag?;
- *      string 'type?;
- * };
- * 
- * - * @since 2.0.0 - */ -public class RecordTypeGenerator extends TypeGenerator { - private final List typeDefinitionNodeList = new ArrayList<>(); - - public RecordTypeGenerator(Schema schema, String typeName) { - super(schema, typeName); - } - - public List getTypeDefinitionNodeList() { - return typeDefinitionNodeList; - } - - /** - * Generate TypeDescriptorNode for object type schemas. - */ - @Override - public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - if (schema.getProperties() != null) { - Map properties = schema.getProperties(); - List required = schema.getRequired(); - List recordFList = addRecordFields(required, properties.entrySet(), typeName); - NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFList); - return NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), - createToken(OPEN_BRACE_TOKEN), fieldNodes, null, createToken(CLOSE_BRACE_TOKEN)); - } else { - NodeList fieldNodes = createEmptyNodeList(); - return NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), - createToken(OPEN_BRACE_TOKEN), fieldNodes, null, createToken(CLOSE_BRACE_TOKEN)); - } - } - - /** - * This util for generating record field with given schema properties. - */ - public List addRecordFields(List required, - Set> fields, - String recordName) throws BallerinaOpenApiException { - // TODO: Handle allOf , oneOf, anyOf - List recordFieldList = new ArrayList<>(); - for (Map.Entry field : fields) { - String fieldNameStr = escapeIdentifier(field.getKey().trim()); - // API doc generations - Schema fieldSchema = field.getValue(); - List schemaDoc = getFieldApiDocs(fieldSchema); - NodeList schemaDocNodes = createNodeList(schemaDoc); - - IdentifierToken fieldName = AbstractNodeFactory.createIdentifierToken(fieldNameStr); - TypeGenerator typeGenerator = getTypeGenerator(fieldSchema, fieldNameStr, recordName); - TypeDescriptorNode fieldTypeName = typeGenerator.generateTypeDescriptorNode(); - if (typeGenerator instanceof ArrayTypeGenerator && - ((ArrayTypeGenerator) typeGenerator).getArrayItemWithConstraint() != null) { - typeDefinitionNodeList.add(((ArrayTypeGenerator) typeGenerator).getArrayItemWithConstraint()); - } - updateRecordFieldList(required, recordFieldList, field, fieldSchema, schemaDocNodes, - fieldName, fieldTypeName); - } - return recordFieldList; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java deleted file mode 100644 index 86760bd55..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; - -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.TypeGeneratorUtils; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.Schema; - -import java.util.List; - -/** - * Generate TypeDefinitionNode and TypeDescriptorNode for anyOf and oneOf schemas. - * -- ex: - * Sample OpenAPI : - *
- *    schemas:
- *     Employee:
- *       anyOf:
- *       - $ref: "#/components/schemas/InternalEmployee"
- *       - $ref: "#/components/schemas/ExternalEmployee"
- *  
- * Generated Ballerina type for the anyOf schema `Employee` : - *
- *  public type Employee InternalEmployee|ExternalEmployee
- * 
- * - * @since 2.0.0 - */ -public class UnionTypeGenerator extends TypeGenerator { - - public UnionTypeGenerator(Schema schema, String typeName) { - super(schema, typeName); - } - - @Override - public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - assert schema instanceof ComposedSchema; - ComposedSchema composedSchema = (ComposedSchema) schema; - List schemas; - if (composedSchema.getOneOf() != null) { - schemas = composedSchema.getOneOf(); - } else { - schemas = composedSchema.getAnyOf(); - } - TypeDescriptorNode unionTypeDesc = TypeGeneratorUtils.getUnionType(schemas, typeName); - return TypeGeneratorUtils.getNullableType(schema, unionTypeDesc); - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/model/GeneratorMetaData.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/model/GeneratorMetaData.java deleted file mode 100644 index 0616a6182..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/model/GeneratorMetaData.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.ballerina.openapi.generators.schema.model; - -import io.swagger.v3.oas.models.OpenAPI; - -/** - * Stores metadata related to Ballerina types generation. - */ -public class GeneratorMetaData { - private final OpenAPI openAPI; - private final boolean nullable; - private static GeneratorMetaData generatorMetaData = null; - - private GeneratorMetaData(OpenAPI openAPI, boolean nullable) { - this.openAPI = openAPI; - this.nullable = nullable; - } - - public static void createInstance(OpenAPI openAPI, boolean nullable) { - generatorMetaData = new GeneratorMetaData(openAPI, nullable); - } - - public static GeneratorMetaData getInstance() { - return generatorMetaData; - } - - public OpenAPI getOpenAPI() { - return openAPI; - } - - public boolean isNullable() { - return nullable; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/BallerinaServiceGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/BallerinaServiceGenerator.java deleted file mode 100644 index 99f552bde..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/BallerinaServiceGenerator.java +++ /dev/null @@ -1,295 +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.openapi.generators.service; - -import io.ballerina.compiler.syntax.tree.ExpressionNode; -import io.ballerina.compiler.syntax.tree.FunctionBodyBlockNode; -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.ListenerDeclarationNode; -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.ParameterNode; -import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.SeparatedNodeList; -import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; -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.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.tools.text.TextDocument; -import io.ballerina.tools.text.TextDocuments; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.Paths; -import io.swagger.v3.oas.models.parameters.RequestBody; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -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.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.createModulePartNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createServiceDeclarationNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorConstants.FUNCTION; -import static io.ballerina.openapi.generators.GeneratorConstants.OAS_PATH_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.RESOURCE; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.generateBodyStatementForComplexUrl; -import static io.ballerina.openapi.generators.GeneratorUtils.getRelativeResourcePath; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.createImportDeclarationNodes; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.generateServiceConfigAnnotation; - -/** - * This Util class use for generating ballerina service file according to given yaml file. - */ -public class BallerinaServiceGenerator { - private boolean isNullableRequired; - private final OpenAPI openAPI; - private final Filter filter; - private final Map typeInclusionRecords = new HashMap<>(); - - public BallerinaServiceGenerator(OpenAPI openAPI, Filter filter) { - this.openAPI = openAPI; - this.filter = filter; - this.isNullableRequired = false; - } - - public List getTypeInclusionRecords() { - List typeRecords = new ArrayList<>(); - this.typeInclusionRecords.forEach((key, value) -> { - typeRecords.add(value); - }); - return typeRecords; - } - - public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { - // Create imports http and openapi - NodeList imports = createImportDeclarationNodes(); - // Need to Generate Base path - ListenerGenerator listener = new ListenerGenerator(); - ListenerDeclarationNode listenerDeclarationNode = listener.getListenerDeclarationNodes(openAPI.getServers()); - NodeList absoluteResourcePath = createBasePathNodeList(listener); - - SimpleNameReferenceNode listenerName = createSimpleNameReferenceNode(listenerDeclarationNode.variableName()); - SeparatedNodeList expressions = createSeparatedNodeList(listenerName); - - // Fill the members with function - List functions = createResourceFunctions(openAPI, filter); - - NodeList members = createNodeList(functions); - // Create annotation if nullable property is enabled - // @http:ServiceConfig { - // treatNilableAsOptional : false - //} - MetadataNode metadataNode = null; - if (isNullableRequired) { - metadataNode = generateServiceConfigAnnotation(); - } - ServiceDeclarationNode serviceDeclarationNode = createServiceDeclarationNode( - metadataNode, createEmptyNodeList(), createToken(SyntaxKind.SERVICE_KEYWORD, - SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE), - null, absoluteResourcePath, createToken(SyntaxKind.ON_KEYWORD, - SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE), expressions, - createToken(SyntaxKind.OPEN_BRACE_TOKEN), members, createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); - - // Create module member declaration - NodeList moduleMembers = createNodeList( - listenerDeclarationNode, serviceDeclarationNode); - - Token eofToken = createIdentifierToken(""); - ModulePartNode modulePartNode = createModulePartNode(imports, moduleMembers, eofToken); - - TextDocument textDocument = TextDocuments.from(""); - SyntaxTree syntaxTree = SyntaxTree.from(textDocument); - return syntaxTree.modifyWith(modulePartNode); - } - - private List createResourceFunctions(OpenAPI openApi, Filter filter) throws BallerinaOpenApiException { - List functions = new ArrayList<>(); - if (!openApi.getPaths().isEmpty()) { - Paths paths = openApi.getPaths(); - Set> pathsItems = paths.entrySet(); - for (Map.Entry path : pathsItems) { - if (!path.getValue().readOperationsMap().isEmpty()) { - Map operationMap = path.getValue().readOperationsMap(); - functions.addAll(applyFiltersForOperations(filter, path.getKey(), operationMap)); - } - } - } - return functions; - } - - private NodeList createBasePathNodeList(ListenerGenerator listener) { - if (OAS_PATH_SEPARATOR.equals(listener.getBasePath())) { - return createNodeList(createIdentifierToken(listener.getBasePath())); - } else { - String[] basePathNode = listener.getBasePath().split(OAS_PATH_SEPARATOR); - List basePath = Arrays.stream(basePathNode).filter(node -> !node.isBlank()) - .map(node -> createIdentifierToken(OAS_PATH_SEPARATOR + - escapeIdentifier(node))).collect(Collectors.toList()); - return createNodeList(basePath); - } - } - - private List applyFiltersForOperations(Filter filter, String path, - Map operationMap) - throws BallerinaOpenApiException { - List functions = new ArrayList<>(); - for (Map.Entry operation : operationMap.entrySet()) { - //Add filter availability - //1.Tag filter - //2.Operation filter - //3. Both tag and operation filter - List filterTags = filter.getTags(); - List operationTags = operation.getValue().getTags(); - List filterOperations = filter.getOperations(); - if (!filterTags.isEmpty() || !filterOperations.isEmpty()) { - if (operationTags != null || ((!filterOperations.isEmpty()) - && (operation.getValue().getOperationId() != null))) { - if ((operationTags != null && GeneratorUtils.hasTags(operationTags, filterTags)) || - ((operation.getValue().getOperationId() != null) && - filterOperations.contains(operation.getValue().getOperationId().trim()))) { - // getRelative resource path - List functionRelativeResourcePath = getRelativeResourcePath(path, operation.getValue()); - // function call - FunctionDefinitionNode functionDefinitionNode = getResourceFunction(operation, - functionRelativeResourcePath, path); - functions.add(functionDefinitionNode); - } - } - } else { - // getRelative resource path - List relativeResourcePath = getRelativeResourcePath(path, operation.getValue()); - // function call - FunctionDefinitionNode resourceFunction = getResourceFunction(operation, relativeResourcePath, path); - functions.add(resourceFunction); - } - } - return functions; - } - - /** - * Generate resource function for given operation. - * - * @param operation - OAS operation - * @param pathNodes - Relative path nodes - * @return - {@link FunctionDefinitionNode} relevant resource - * @throws BallerinaOpenApiException when the process failure occur - */ - private FunctionDefinitionNode getResourceFunction(Map.Entry operation, - List pathNodes, String path) - throws BallerinaOpenApiException { - NodeList qualifiersList = createNodeList(createIdentifierToken(RESOURCE, SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE)); - Token functionKeyWord = createIdentifierToken(FUNCTION, SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - IdentifierToken functionName = createIdentifierToken(operation.getKey().name() - .toLowerCase(Locale.ENGLISH), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - NodeList relativeResourcePath = createNodeList(pathNodes); - ParametersGenerator parametersGenerator = new ParametersGenerator(false); - parametersGenerator.generateResourcesInputs(operation); - List params = new ArrayList<>(parametersGenerator.getRequiredParams()); - - // Handle request Body (Payload) - if (operation.getValue().getRequestBody() != null) { - RequestBody requestBody = operation.getValue().getRequestBody(); - requestBody = resolveRequestBodyReference(requestBody); - if (requestBody.getContent() != null) { - RequestBodyGenerator requestBodyGen = new RequestBodyGenerator(this.openAPI.getComponents(), - requestBody); - params.add(requestBodyGen.createNodeForRequestBody()); - params.add(createToken(SyntaxKind.COMMA_TOKEN)); - } - } - - // For creating the order of the parameters in the function - if (!parametersGenerator.getDefaultableParams().isEmpty()) { - params.addAll(parametersGenerator.getDefaultableParams()); - } - if (params.size() > 1) { - params.remove(params.size() - 1); - } - - if (!isNullableRequired) { - isNullableRequired = parametersGenerator.isNullableRequired(); - } - SeparatedNodeList parameters = createSeparatedNodeList(params); - ReturnTypeGenerator returnTypeGenerator = new ReturnTypeGenerator(); - ReturnTypeDescriptorNode returnNode = returnTypeGenerator.getReturnTypeDescriptorNode(operation, - createEmptyNodeList(), path); - typeInclusionRecords.putAll(returnTypeGenerator.getTypeInclusionRecords()); - - FunctionSignatureNode functionSignatureNode = createFunctionSignatureNode( - createToken(SyntaxKind.OPEN_PAREN_TOKEN), - parameters, createToken(SyntaxKind.CLOSE_PAREN_TOKEN), returnNode); - - // Function Body Node - // If path parameter has some special characters, extra body statements are added to handle the complexity. - List bodyStatements = generateBodyStatementForComplexUrl(path); - FunctionBodyBlockNode functionBodyBlockNode = createFunctionBodyBlockNode( - createToken(SyntaxKind.OPEN_BRACE_TOKEN), - null, - bodyStatements.isEmpty() ? - createEmptyNodeList() : - createNodeList(bodyStatements), - createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); - - return createFunctionDefinitionNode(SyntaxKind.RESOURCE_ACCESSOR_DEFINITION, null, - qualifiersList, functionKeyWord, functionName, relativeResourcePath, functionSignatureNode, - functionBodyBlockNode); - } - - /** - * Resolve requestBody reference. - */ - private RequestBody resolveRequestBodyReference(RequestBody requestBody) throws BallerinaOpenApiException { - if (requestBody.get$ref() != null) { - String requestBodyName = extractReferenceType(requestBody.get$ref()); - requestBody = resolveRequestBodyReference(openAPI.getComponents() - .getRequestBodies().get(requestBodyName.trim())); - } - return requestBody; - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ParametersGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ParametersGenerator.java deleted file mode 100644 index 34051bea5..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ParametersGenerator.java +++ /dev/null @@ -1,444 +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.openapi.generators.service; - -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.BuiltinSimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; -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.OptionalTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.ParameterNode; -import io.ballerina.compiler.syntax.tree.RequiredParameterNode; -import io.ballerina.compiler.syntax.tree.SyntaxKind; -import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.Content; -import io.swagger.v3.oas.models.media.MapSchema; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.ObjectSchema; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.parameters.Parameter; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -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.createArrayTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createDefaultableParameterNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_JSON; -import static io.ballerina.openapi.generators.GeneratorConstants.ARRAY; -import static io.ballerina.openapi.generators.GeneratorConstants.HEADER; -import static io.ballerina.openapi.generators.GeneratorConstants.HEADER_ANNOT; -import static io.ballerina.openapi.generators.GeneratorConstants.MAP_JSON; -import static io.ballerina.openapi.generators.GeneratorConstants.OBJECT; -import static io.ballerina.openapi.generators.GeneratorConstants.QUERY; -import static io.ballerina.openapi.generators.GeneratorConstants.STRING; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.convertOpenAPITypeToBallerina; -import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_103; -import static io.ballerina.openapi.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_104; -import static io.ballerina.openapi.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_105; -import static io.ballerina.openapi.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_106; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.getAnnotationNode; - -/** - * This class uses for generating all resource function parameters. - * - * @since 2.0.0 - */ -public class ParametersGenerator { - - private boolean isNullableRequired; - private List requiredParams; - private List defaultableParams; - public ParametersGenerator(boolean isNullableRequired) { - this.isNullableRequired = isNullableRequired; - this.requiredParams = new ArrayList<>(); - this.defaultableParams = new ArrayList<>(); - } - - public List getRequiredParams() { - return requiredParams; - } - - public List getDefaultableParams() { - return defaultableParams; - } - - public boolean isNullableRequired() { - return isNullableRequired; - } - /** - * This function for generating operation parameters. - * - * @param operation OAS operation - * @throws BallerinaOpenApiException when the parameter generation fails. - */ - public void generateResourcesInputs(Map.Entry operation) - throws BallerinaOpenApiException { - Token comma = createToken(SyntaxKind.COMMA_TOKEN); - // Handle header and query parameters - if (operation.getValue().getParameters() != null) { - List parameters = operation.getValue().getParameters(); - for (Parameter parameter: parameters) { - if (parameter.getIn().trim().equals(HEADER)) { - ParameterNode param = handleHeader(parameter); - if (param.kind() == SyntaxKind.DEFAULTABLE_PARAM) { - defaultableParams.add(param); - defaultableParams.add(comma); - } else { - requiredParams.add(param); - requiredParams.add(comma); - } - } else if (parameter.getIn().trim().equals(QUERY)) { - if (parameter.getRequired() != null && parameter.getRequired() && - (parameter.getSchema().getNullable() != null && parameter.getSchema().getNullable())) { - isNullableRequired = true; - } - // type BasicType boolean|int|float|decimal|string ; - // public type () |BasicType|BasicType []| map; - Node param = createNodeForQueryParam(parameter); - if (param.kind() == SyntaxKind.DEFAULTABLE_PARAM) { - defaultableParams.add(param); - defaultableParams.add(comma); - } else { - requiredParams.add(param); - requiredParams.add(comma); - } - } - } - } - } - - /** - * This function for generating parameter ST node for header. - *
 resource function get pets(@http:Header {name:"x-request-id"} string header) 
- */ - private ParameterNode handleHeader(Parameter parameter)throws BallerinaOpenApiException { - Schema schema = parameter.getSchema(); - TypeDescriptorNode headerTypeName; - IdentifierToken parameterName = createIdentifierToken(escapeIdentifier(parameter.getName() - .toLowerCase(Locale.ENGLISH)), AbstractNodeFactory.createEmptyMinutiaeList(), SINGLE_WS_MINUTIAE); - if (schema.getType() == null) { - // Header example: - // 01.
-             //       in: header
-             //       name: X-Request-ID
-             //       schema: {}
-             //  
- throw new BallerinaOpenApiException(String.format(OAS_SERVICE_106.getDescription(), parameter.getName())); - } else { - if (!schema.getType().equals(STRING) && !(schema instanceof ArraySchema)) { - throw new BallerinaOpenApiException(String.format(OAS_SERVICE_105.getDescription(), - parameter.getName(), schema.getType())); - } else if (schema instanceof ArraySchema) { - Schema items = ((ArraySchema) schema).getItems(); - if (items.getType() == null) { - throw new BallerinaOpenApiException(String.format(OAS_SERVICE_104.getDescription(), - parameter.getName())); - } else if (!items.getType().equals(STRING)) { - throw new BallerinaOpenApiException(String.format(OAS_SERVICE_103.getDescription(), - parameter.getName(), items.getType())); - } - BuiltinSimpleNameReferenceNode headerArrayItemTypeName = createBuiltinSimpleNameReferenceNode( - null, createIdentifierToken(STRING)); - ArrayDimensionNode dimensionNode = - NodeFactory.createArrayDimensionNode(createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - NodeList nodeList = createNodeList(dimensionNode); - headerTypeName = createArrayTypeDescriptorNode(headerArrayItemTypeName, nodeList); - } else { - headerTypeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken( - convertOpenAPITypeToBallerina(schema.getType().trim()), SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE)); - } - // Create annotation for header - // TODO: This code block is to be enabled when handle the headers handle additional parameters - // MappingConstructorExpressionNode annotValue = NodeFactory.createMappingConstructorExpressionNode( - // createToken(SyntaxKind.OPEN_BRACE_TOKEN), NodeFactory.createSeparatedNodeList(), - // createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); - - AnnotationNode headerNode = getAnnotationNode(HEADER_ANNOT, null); - NodeList headerAnnotations = createNodeList(headerNode); - // Handle optional values in headers - if (!parameter.getRequired()) { - // If optional it behaves like default value with null ex:(string? header) - headerTypeName = createOptionalTypeDescriptorNode(headerTypeName, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - } - // Handle default values in headers - if (schema.getDefault() != null) { - return getDefaultableHeaderNode(schema, headerTypeName, parameterName, headerAnnotations); - } - // Handle header with parameter required true and nullable ture ex: (string? header) - if (parameter.getRequired() && schema.getNullable() != null && schema.getNullable().equals(true)) { - isNullableRequired = true; - headerTypeName = createOptionalTypeDescriptorNode(headerTypeName, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - } - return createRequiredParameterNode(headerAnnotations, headerTypeName, parameterName); - } - } - - /** - * Generate ballerina default headers. - */ - private DefaultableParameterNode getDefaultableHeaderNode(Schema schema, TypeDescriptorNode headerTypeName, - IdentifierToken parameterName, - NodeList headerAnnotations) { - if (!schema.getType().equals(ARRAY)) { - return createDefaultableParameterNode(headerAnnotations, headerTypeName, parameterName, - createToken(SyntaxKind.EQUAL_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken("\"" + - schema.getDefault().toString() + "\""))); - } - return createDefaultableParameterNode(headerAnnotations, headerTypeName, parameterName, - createToken(SyntaxKind.EQUAL_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); - } - - /** - * This for generate query parameter nodes. - * - * Ballerina support query parameter types : - * type BasicType boolean|int|float|decimal|string ; - * public type QueryParamType json | () |BasicType|BasicType[]; - */ - private Node createNodeForQueryParam(Parameter parameter) throws BallerinaOpenApiException { - Schema schema = parameter.getSchema(); - NodeList annotations = createEmptyNodeList(); - IdentifierToken parameterName = createIdentifierToken(escapeIdentifier(parameter.getName().trim()), - AbstractNodeFactory.createEmptyMinutiaeList(), SINGLE_WS_MINUTIAE); - boolean isSchemaSupported = schema == null || schema.get$ref() != null || schema.getType() == null - || schema.getType().equals(OBJECT) || schema instanceof ObjectSchema || schema.getProperties() != null; - if (parameter.getContent() != null) { - Content content = parameter.getContent(); - for (Map.Entry mediaTypeEntry : content.entrySet()) { - return handleMapJsonQueryParameter(parameter, annotations, parameterName, mediaTypeEntry); - } - } else if (isSchemaSupported) { - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; - throw new BallerinaOpenApiException(String.format(messages.getDescription(), - parameter.getSchema().getType())); - } else if (parameter.getSchema().getDefault() != null) { - // When query parameter has default value - return handleDefaultQueryParameter(schema, annotations, parameterName); - } else if (parameter.getRequired() && schema.getNullable() == null) { - // Required typeDescriptor - return handleRequiredQueryParameter(schema, annotations, parameterName); - } else { - // Optional typeDescriptor - return handleOptionalQueryParameter(schema, annotations, parameterName); - } - return null; - } - - /** - * Handle query parameter for content type which has application/json. - * example: - *
-     *     parameters:
-     *         - name: petType
-     *           in: query
-     *           content:
-     *             application/json:
-     *               schema:
-     *                 type: object
-     *                 additionalProperties: true
-     * 
- */ - private RequiredParameterNode handleMapJsonQueryParameter(Parameter parameter, NodeList annotations, - IdentifierToken parameterName, - Map.Entry mediaTypeEntry) - throws BallerinaOpenApiException { - - if (mediaTypeEntry.getKey().equals(APPLICATION_JSON) && - mediaTypeEntry.getValue().getSchema() instanceof MapSchema) { - if (parameter.getRequired()) { - BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(MAP_JSON)); - return createRequiredParameterNode(annotations, rTypeName, parameterName); - } else { - BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(MAP_JSON)); - OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(rTypeName, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - return createRequiredParameterNode(annotations, optionalNode, parameterName); - } - } else { - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; - throw new BallerinaOpenApiException(String.format(messages.getDescription(), - "content")); - } - } - - /** - * This function is to handle query schema which is not have required true. - */ - private Node handleOptionalQueryParameter(Schema schema, NodeList annotations, - IdentifierToken parameterName) throws BallerinaOpenApiException { - if (schema instanceof ArraySchema) { - Schema items = ((ArraySchema) schema).getItems(); - if (items.getType() == null) { - // Resource function doesn't support to query parameters with array type which doesn't have an - // item type. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; - throw new BallerinaOpenApiException(messages.getDescription()); - } else if (!(items instanceof ObjectSchema) && !(items.getType().equals(ARRAY))) { - // create arrayTypeDescriptor - ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); - OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(arrayTypeName, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - return createRequiredParameterNode(annotations, optionalNode, parameterName); - } else if (items.getType().equals(ARRAY)) { - // Resource function doesn't support to the nested array type query parameters. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; - throw new BallerinaOpenApiException(messages.getDescription()); - } else { - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; - throw new BallerinaOpenApiException(String.format(messages.getDescription(), "object")); - } - } else { - Token name = createIdentifierToken(convertOpenAPITypeToBallerina( - schema.getType().toLowerCase(Locale.ENGLISH).trim()), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, name); - OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(rTypeName, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - return createRequiredParameterNode(annotations, optionalNode, parameterName); - } - } - - private Node handleRequiredQueryParameter(Schema schema, NodeList annotations, - IdentifierToken parameterName) throws BallerinaOpenApiException { - if (schema instanceof ArraySchema) { - Schema items = ((ArraySchema) schema).getItems(); - if (!(items instanceof ArraySchema) && items.getType() != null) { - ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); - return createRequiredParameterNode(annotations, arrayTypeName, parameterName); - } else if (items.getType() == null) { - // Resource function doesn't support query parameters for array types that doesn't have an item type. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; - throw new BallerinaOpenApiException(messages.getDescription()); - } else if (items instanceof ObjectSchema) { - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; - throw new BallerinaOpenApiException(String.format(messages.getDescription(), "object")); - } else { - // Resource function doesn't support to the nested array type query parameters. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; - throw new BallerinaOpenApiException(messages.getDescription()); - } - } else { - Token name = createIdentifierToken(convertOpenAPITypeToBallerina( - schema.getType().toLowerCase(Locale.ENGLISH).trim()), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, name); - return createRequiredParameterNode(annotations, rTypeName, parameterName); - } - } - - /** - * This function generate default query parameter when OAS gives default value. - * - * OAS code example: - *
-     *      parameters:
-     *         - name: limit
-     *           in: query
-     *           schema:
-     *             type: integer
-     *             default: 10
-     *             format: int32
-     *  
- * generated ballerina -> int limit = 10; - */ - - private Node handleDefaultQueryParameter(Schema schema, NodeList annotations, - IdentifierToken parameterName) throws BallerinaOpenApiException { - if (schema instanceof ArraySchema) { - Schema items = ((ArraySchema) schema).getItems(); - if (!(items instanceof ArraySchema) && items.getType() != null) { - ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); - return createDefaultableParameterNode(annotations, arrayTypeName, parameterName, - createToken(SyntaxKind.EQUAL_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); - } else if (items.getType() == null) { - // Resource function doesn't support to query parameters with array type which hasn't item type. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; - throw new BallerinaOpenApiException(messages.getDescription()); - } else { - // Resource function doesn't support to the nested array type query parameters. - ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; - throw new BallerinaOpenApiException(messages.getDescription()); - } - } else { - Token name = createIdentifierToken(convertOpenAPITypeToBallerina( - schema.getType().toLowerCase(Locale.ENGLISH).trim()), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, name); - if (schema.getType().equals(STRING)) { - return createDefaultableParameterNode(annotations, rTypeName, parameterName, - createToken(SyntaxKind.EQUAL_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken('"' + - schema.getDefault().toString() + '"'))); - } - return createDefaultableParameterNode(annotations, rTypeName, parameterName, - createToken(SyntaxKind.EQUAL_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); - } - } - - - // Create ArrayTypeDescriptorNode using Schema - private ArrayTypeDescriptorNode getArrayTypeDescriptorNode(Schema items) throws BallerinaOpenApiException { - - Token arrayName = createIdentifierToken(convertOpenAPITypeToBallerina(items.getType().toLowerCase( - Locale.ENGLISH).trim()), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - BuiltinSimpleNameReferenceNode memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, arrayName); - ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( - createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - NodeList nodeList = createNodeList(dimensionNode); - - if (items.getNullable() != null && items.getNullable()) { - // generate -> int?[] - OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(memberTypeDesc, - createToken(SyntaxKind.QUESTION_MARK_TOKEN)); - return createArrayTypeDescriptorNode(optionalNode, nodeList); - } - // generate -> int[] - return createArrayTypeDescriptorNode(memberTypeDesc, nodeList); - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/RequestBodyGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/RequestBodyGenerator.java deleted file mode 100644 index f8a836c03..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/RequestBodyGenerator.java +++ /dev/null @@ -1,255 +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.openapi.generators.service; -import io.ballerina.compiler.syntax.tree.AnnotationNode; -import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; -import io.ballerina.compiler.syntax.tree.BasicLiteralNode; -import io.ballerina.compiler.syntax.tree.IdentifierToken; -import io.ballerina.compiler.syntax.tree.ListConstructorExpressionNode; -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.NodeFactory; -import io.ballerina.compiler.syntax.tree.NodeList; -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 io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.parameters.RequestBody; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -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.createToken; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_JSON; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_OCTET_STREAM; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_URL_ENCODE; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_XML; -import static io.ballerina.openapi.generators.GeneratorConstants.MEDIA_TYPE_KEYWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.PAYLOAD; -import static io.ballerina.openapi.generators.GeneratorConstants.PAYLOAD_KEYWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.TEXT; -import static io.ballerina.openapi.generators.GeneratorConstants.TEXT_WILDCARD_REGEX; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.extractReferenceType; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.getAnnotationNode; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.getMediaTypeToken; - -/** - * This class for generating request body payload for OAS requestBody section. - * - * @since 2.0.0 - */ -public class RequestBodyGenerator { - private final Components components; - private final RequestBody requestBody; - - public RequestBodyGenerator(Components components, RequestBody requestBody) { - this.components = components; - this.requestBody = requestBody; - } - - /** - * This for creating request Body for given request object. - */ - public RequiredParameterNode createNodeForRequestBody() - throws BallerinaOpenApiException { - // type CustomRecord record {| anydata...; |}; - // public type PayloadType string|json|xml|byte[]|CustomRecord|CustomRecord[] ; - List literals = new ArrayList<>(); - MappingConstructorExpressionNode annotValue = null; - TypeDescriptorNode typeName; - // Filter same data type - HashSet> equalDataType = filterMediaTypes(requestBody); - if (!equalDataType.isEmpty()) { - typeName = getNodeForPayloadType(components, equalDataType.iterator().next()); - SeparatedNodeList fields = fillRequestAnnotationValues(literals, equalDataType); - annotValue = NodeFactory.createMappingConstructorExpressionNode( - createToken(SyntaxKind.OPEN_BRACE_TOKEN), fields, createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); - } else { - Iterator> content = requestBody.getContent().entrySet().iterator(); - Map.Entry mime = content.next(); - equalDataType.add(mime); - typeName = getNodeForPayloadType(components, mime); - if (mime.getKey().equals(APPLICATION_URL_ENCODE)) { - SeparatedNodeList fields = fillRequestAnnotationValues(literals, equalDataType); - annotValue = NodeFactory.createMappingConstructorExpressionNode( - createToken(SyntaxKind.OPEN_BRACE_TOKEN), fields, createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); - } - } - AnnotationNode annotationNode = getAnnotationNode(PAYLOAD_KEYWORD, annotValue); - NodeList annotation = NodeFactory.createNodeList(annotationNode); - Token paramName = createIdentifierToken(PAYLOAD, SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - return createRequiredParameterNode(annotation, typeName, paramName); - } - - /** - * This util function is for generating type node for request payload in resource function. - */ - private TypeDescriptorNode getNodeForPayloadType(Components components, Map.Entry mediaType) - throws BallerinaOpenApiException { - TypeDescriptorNode typeName; - if (mediaType.getValue().getSchema().get$ref() != null) { - String schemaName = extractReferenceType(mediaType.getValue().getSchema().get$ref()); - Map schemas = components.getSchemas(); - String mediaTypeContent = mediaType.getKey().trim(); - if (mediaTypeContent.matches(TEXT_WILDCARD_REGEX)) { - mediaTypeContent = TEXT; - } - IdentifierToken identifierToken; - switch (mediaTypeContent) { - case APPLICATION_XML: - identifierToken = createIdentifierToken(GeneratorConstants.XML); - typeName = createSimpleNameReferenceNode(identifierToken); - break; - case TEXT: - identifierToken = createIdentifierToken(GeneratorConstants.STRING); - typeName = createSimpleNameReferenceNode(identifierToken); - break; - case APPLICATION_OCTET_STREAM: - ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( - createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - typeName = createArrayTypeDescriptorNode(createBuiltinSimpleNameReferenceNode( - null, createIdentifierToken(GeneratorConstants.BYTE)), - NodeFactory.createNodeList(dimensionNode)); - break; - case APPLICATION_JSON: - Schema schema = schemas.get(getValidName(schemaName, true)); - // This condition is to avoid wrong code generation for union type request body. If given schema - // has oneOf type , then it will not be able to support via ballerina. We need to pick it mime - // type instead of schema type. - if ((schema instanceof ComposedSchema) && (((ComposedSchema) schema).getOneOf() != null)) { - identifierToken = createIdentifierToken(GeneratorConstants.JSON); - typeName = createSimpleNameReferenceNode(identifierToken); - } else { - typeName = createSimpleNameReferenceNode(createIdentifierToken( - getValidName(schemaName, true))); - } - break; - case APPLICATION_URL_ENCODE: - typeName = createSimpleNameReferenceNode(createIdentifierToken( - getValidName(schemaName, true))); - break; - default: - identifierToken = createIdentifierToken(GeneratorConstants.JSON); - typeName = createSimpleNameReferenceNode(identifierToken); - } - } else { - typeName = getMediaTypeToken(mediaType); - } - return typeName; - } - - /** - * This function fill the annotation values. - * - * 01. when field has some override media type - *
 @http:Payload{mediaType: "application/x-www-form-urlencoded"} User payload
- * 02. when field has list media value - *
 @http:Payload{mediaType: ["application/json", "application/snowflake+json"]} User payload
- * - */ - private SeparatedNodeList fillRequestAnnotationValues(List literals, - HashSet> equalDataTypes) { - Token comma = createToken(SyntaxKind.COMMA_TOKEN); - IdentifierToken mediaType = createIdentifierToken(MEDIA_TYPE_KEYWORD); - - Iterator> iter = equalDataTypes.iterator(); - SpecificFieldNode specificFieldNode; - while (iter.hasNext()) { - Map.Entry next = iter.next(); - literals.add(createIdentifierToken('"' + next.getKey().trim() + '"', SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE)); - literals.add(comma); - } - literals.remove(literals.size() - 1); - SeparatedNodeList expression = NodeFactory.createSeparatedNodeList(literals); - if (equalDataTypes.size() == 1) { - BasicLiteralNode valueExpr = NodeFactory.createBasicLiteralNode(SyntaxKind.STRING_LITERAL, - createIdentifierToken('"' + equalDataTypes.iterator().next().getKey() + '"')); - specificFieldNode = NodeFactory.createSpecificFieldNode(null, mediaType, - createToken(SyntaxKind.COLON_TOKEN), valueExpr); - } else { - ListConstructorExpressionNode valueExpr = NodeFactory.createListConstructorExpressionNode( - createToken(SyntaxKind.OPEN_BRACKET_TOKEN), expression, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - specificFieldNode = NodeFactory.createSpecificFieldNode(null, mediaType, - createToken(SyntaxKind.COLON_TOKEN), valueExpr); - } - return NodeFactory.createSeparatedNodeList(specificFieldNode); - } - - //Extract same datatype - private HashSet> filterMediaTypes(RequestBody requestBody) - throws BallerinaOpenApiException { - HashSet> equalDataType = new HashSet<>(); - Set> entries = requestBody.getContent().entrySet(); - Iterator> iterator = entries.iterator(); - List> updatedEntries = new ArrayList<>(entries); - while (iterator.hasNext()) { - // Remove element from updateEntries - Map.Entry mediaTypeEntry = iterator.next(); - updatedEntries.remove(mediaTypeEntry); - if (!updatedEntries.isEmpty()) { - getSameDataTypeMedia(equalDataType, updatedEntries, mediaTypeEntry); - if (!equalDataType.isEmpty()) { - equalDataType.add(mediaTypeEntry); - break; - } - } - } - return equalDataType; - } - - private void getSameDataTypeMedia(HashSet> equalDataType, - List> updatedEntries, - Map.Entry mediaTypeEntry) throws BallerinaOpenApiException { - for (Map.Entry updateNext : updatedEntries) { - MediaType parentValue = mediaTypeEntry.getValue(); - MediaType childValue = updateNext.getValue(); - if (parentValue.getSchema().get$ref() != null && childValue.getSchema().get$ref() != null) { - String parentRef = parentValue.getSchema().get$ref().trim(); - String childRef = childValue.getSchema().get$ref().trim(); - if (extractReferenceType(parentRef).equals(extractReferenceType(childRef))) { - equalDataType.add(updateNext); - } - } - } - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ReturnTypeGenerator.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ReturnTypeGenerator.java deleted file mode 100644 index a495abbd1..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ReturnTypeGenerator.java +++ /dev/null @@ -1,320 +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.openapi.generators.service; - -import io.ballerina.compiler.syntax.tree.AnnotationNode; -import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.IdentifierToken; -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.RecordFieldNode; -import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; -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.TypeReferenceNode; -import io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.Content; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.responses.ApiResponse; -import io.swagger.v3.oas.models.responses.ApiResponses; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -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.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.createRecordFieldNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createRecordTypeDescriptorNode; -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.createTypeDefinitionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_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.TYPE_KEYWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.BODY; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.getQualifiedNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.isComplexURL; -import static io.ballerina.openapi.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_107; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.extractReferenceType; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.getMediaTypeToken; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.getUnionNodeForOneOf; - -/** - * This class for generating return type definition node according to the OpenAPI specification response section. - * - * @since 2.0.0 - */ -public class ReturnTypeGenerator { - private final Map typeInclusionRecords = new HashMap<>(); - - public Map getTypeInclusionRecords() { - return this.typeInclusionRecords; - } - /** - * This function used to generate return function node in the function signature. - * Payload media type will not be added to the annotation. - * @param operation OpenApi operation - * @param annotations Annotation node list - * @return return returnNode - * @throws BallerinaOpenApiException - */ - public ReturnTypeDescriptorNode getReturnTypeDescriptorNode(Map.Entry operation, - NodeList annotations, String path) - throws BallerinaOpenApiException { - - Token returnKeyWord = createIdentifierToken("returns", SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - ReturnTypeDescriptorNode returnNode = null; - if (operation.getValue().getResponses() != null) { - ApiResponses responses = operation.getValue().getResponses(); - Iterator> responseIter = responses.entrySet().iterator(); - if (responses.size() > 1) { - UnionTypeDescriptorNode type = getUnionNode(responseIter); - returnNode = createReturnTypeDescriptorNode(returnKeyWord, annotations, type); - } else { - while (responseIter.hasNext()) { - Map.Entry response = responseIter.next(); - if (response.getValue().getContent() == null && - response.getValue().get$ref() == null || response.getValue().getContent().size() == 0) { - String code = GeneratorConstants.HTTP_CODES_DES.get(response.getKey().trim()); - // Scenario 01: Response has single response without content type - TypeDescriptorNode statues; - if (response.getKey().trim().equals(GeneratorConstants.DEFAULT)) { - statues = createSimpleNameReferenceNode(createIdentifierToken( - GeneratorConstants.HTTP_RESPONSE)); - } else { - statues = getQualifiedNameReferenceNode(GeneratorConstants.HTTP, code); - } - returnNode = createReturnTypeDescriptorNode(returnKeyWord, annotations, statues); - } else if (response.getValue().getContent() != null) { - if (response.getKey().trim().equals(GeneratorConstants.HTTP_200)) { - Iterator> iterator = response.getValue().getContent() - .entrySet().iterator(); - if (response.getValue().getContent().entrySet().size() > 1) { - returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), - getUnionNodeForContent(iterator)); - } else { - while (iterator.hasNext()) { - Map.Entry next = iterator.next(); - returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), - getMediaTypeToken(next)); - } - } - } else if (response.getKey().trim().equals(GeneratorConstants.DEFAULT)) { - BuiltinSimpleNameReferenceNode type = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(GeneratorConstants.HTTP_RESPONSE)); - returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), type); - } else { - String code = GeneratorConstants.HTTP_CODES_DES.get(response.getKey().trim()); - Content content = response.getValue().getContent(); - Iterator> contentItr = content.entrySet().iterator(); - TypeDescriptorNode type; - if (content.entrySet().size() > 1) { - type = getUnionNodeForContent(contentItr); - } else { - // Handle for only first content type - type = getNodeForContent(contentItr); - } - SimpleNameReferenceNode recordType = createReturnTypeInclusionRecord(code, type); - NodeList annotation = createEmptyNodeList(); - returnNode = createReturnTypeDescriptorNode(returnKeyWord, annotation, recordType); - } - } - } - } - } else { - // --error node TypeDescriptor - returnNode = createReturnTypeDescriptorNode(createToken(SyntaxKind.RETURNS_KEYWORD), createEmptyNodeList(), - createSimpleNameReferenceNode(createIdentifierToken("error?"))); - } - if (isComplexURL(path)) { - assert returnNode != null; - String returnStatement = returnNode.toString().trim().replace("returns", "") + "|error"; - return createReturnTypeDescriptorNode(createToken(SyntaxKind.RETURNS_KEYWORD), createEmptyNodeList(), - createSimpleNameReferenceNode(createIdentifierToken(returnStatement))); - } - return returnNode; - } - - /** - * This function uses to handle the content details in OAS to map ballerina return node. - * @param contentItr - Media type from OAS - * @return - {@link TypeDescriptorNode} for content type in ballerina - * @throws BallerinaOpenApiException proceed when the process break. - */ - private TypeDescriptorNode getNodeForContent(Iterator> contentItr) - throws BallerinaOpenApiException { - String dataType; - TypeDescriptorNode type = null; - while (contentItr.hasNext()) { - Map.Entry mediaTypeEntry = contentItr.next(); - if (mediaTypeEntry.getValue().getSchema() != null) { - Schema schema = mediaTypeEntry.getValue().getSchema(); - if (schema.get$ref() != null) { - dataType = getValidName(extractReferenceType(schema.get$ref().trim()), true); - type = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(dataType)); - } else if (schema instanceof ComposedSchema) { - Iterator iterator = ((ComposedSchema) schema).getOneOf().iterator(); - type = getUnionNodeForOneOf(iterator); - } else { - type = getMediaTypeToken(mediaTypeEntry); - } - } - } - return type; - } - - /** - * Generate union type node when operation has multiple responses. - */ - private UnionTypeDescriptorNode getUnionNode(Iterator> responseIter) - throws BallerinaOpenApiException { - List qualifiedNodes = new ArrayList<>(); - Token pipeToken = createToken(SyntaxKind.PIPE_TOKEN); - while (responseIter.hasNext()) { - Map.Entry response = responseIter.next(); - String responseCode = response.getKey().trim(); - String code = GeneratorConstants.HTTP_CODES_DES.get(responseCode); - - if (code == null && !responseCode.equals(GeneratorConstants.DEFAULT)) { - throw new BallerinaOpenApiException(String.format(OAS_SERVICE_107.getDescription(), responseCode)); - } - - if (responseCode.equals(GeneratorConstants.DEFAULT)) { - TypeDescriptorNode record = createSimpleNameReferenceNode(createIdentifierToken( - GeneratorConstants.HTTP_RESPONSE)); - qualifiedNodes.add(record); - } else if (response.getValue().getContent() == null && response.getValue().get$ref() == null || - response.getValue().getContent() != null && response.getValue().getContent().size() == 0) { - //key and value - QualifiedNameReferenceNode node = getQualifiedNameReferenceNode(GeneratorConstants.HTTP, code); - qualifiedNodes.add(node); - } else if (response.getValue().getContent() != null) { - TypeDescriptorNode record = getMediaTypeToken(response.getValue().getContent().entrySet() - .iterator().next()); - if (responseCode.equals(GeneratorConstants.HTTP_200)) { - qualifiedNodes.add(record); - } else { - SimpleNameReferenceNode node = createReturnTypeInclusionRecord(code, record); - qualifiedNodes.add(node); - } - } - } - TypeDescriptorNode right = qualifiedNodes.get(qualifiedNodes.size() - 1); - TypeDescriptorNode traversRight = qualifiedNodes.get(qualifiedNodes.size() - 2); - UnionTypeDescriptorNode traversUnion = createUnionTypeDescriptorNode(traversRight, pipeToken, right); - if (qualifiedNodes.size() >= 3) { - for (int i = qualifiedNodes.size() - 3; i >= 0; i--) { - traversUnion = createUnionTypeDescriptorNode(qualifiedNodes.get(i), pipeToken, traversUnion); - } - } - return traversUnion; - } - - /** - * Generate union type node when response has multiple content types. - */ - private UnionTypeDescriptorNode getUnionNodeForContent(Iterator> iterator) - throws BallerinaOpenApiException { - List qualifiedNodes = new ArrayList<>(); - Token pipeToken = createIdentifierToken("|"); - while (iterator.hasNext()) { - Map.Entry contentType = iterator.next(); - TypeDescriptorNode node = getMediaTypeToken(contentType); - qualifiedNodes.add((SimpleNameReferenceNode) node); - } - SimpleNameReferenceNode right = qualifiedNodes.get(qualifiedNodes.size() - 1); - SimpleNameReferenceNode traversRight = qualifiedNodes.get(qualifiedNodes.size() - 2); - UnionTypeDescriptorNode traversUnion = createUnionTypeDescriptorNode(traversRight, pipeToken, right); - if (qualifiedNodes.size() >= 3) { - for (int i = qualifiedNodes.size() - 3; i >= 0; i--) { - traversUnion = createUnionTypeDescriptorNode(qualifiedNodes.get(i), pipeToken, traversUnion); - } - } - return traversUnion; - } - - /** - * Create recordType TypeDescriptor. - */ - private SimpleNameReferenceNode createReturnTypeInclusionRecord(String statusCode, TypeDescriptorNode type) { - String recordName = statusCode + getValidName(type.toString(), true); - Token recordKeyWord = createToken(RECORD_KEYWORD); - Token bodyStartDelimiter = createIdentifierToken("{|"); - // Create record fields - List recordFields = new ArrayList<>(); - // Type reference node - Token asteriskToken = createIdentifierToken("*"); - QualifiedNameReferenceNode typeNameField = getQualifiedNameReferenceNode(GeneratorConstants.HTTP, statusCode); - TypeReferenceNode typeReferenceNode = createTypeReferenceNode( - asteriskToken, - typeNameField, - createToken(SyntaxKind.SEMICOLON_TOKEN)); - recordFields.add(typeReferenceNode); - - IdentifierToken fieldName = createIdentifierToken(BODY, SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); - RecordFieldNode recordFieldNode = createRecordFieldNode( - null, null, - type, - fieldName, null, - createToken(SyntaxKind.SEMICOLON_TOKEN)); - recordFields.add(recordFieldNode); - - NodeList fieldsList = createSeparatedNodeList(recordFields); - Token bodyEndDelimiter = createIdentifierToken("|}"); - - RecordTypeDescriptorNode recordTypeDescriptorNode = createRecordTypeDescriptorNode( - recordKeyWord, - bodyStartDelimiter, - fieldsList, null, - bodyEndDelimiter); - - TypeDefinitionNode typeDefinitionNode = createTypeDefinitionNode(null, - createToken(PUBLIC_KEYWORD), - createToken(TYPE_KEYWORD), - createIdentifierToken(recordName), - recordTypeDescriptorNode, - createToken(SEMICOLON_TOKEN)); - - typeInclusionRecords.put(recordName, typeDefinitionNode); - - return createSimpleNameReferenceNode(createIdentifierToken(recordName)); - } -} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceGenerationUtils.java b/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceGenerationUtils.java deleted file mode 100644 index 3932c39ed..000000000 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceGenerationUtils.java +++ /dev/null @@ -1,251 +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.openapi.generators.service; - -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.BasicLiteralNode; -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.MetadataNode; -import io.ballerina.compiler.syntax.tree.NodeFactory; -import io.ballerina.compiler.syntax.tree.NodeList; -import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; -import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.SpecificFieldNode; -import io.ballerina.compiler.syntax.tree.SyntaxKind; -import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.Schema; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyMinutiaeList; -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.createAnnotationNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBasicLiteralNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; -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.createSimpleNameReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSpecificFieldNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_LITERAL; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_JSON; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_OCTET_STREAM; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_URL_ENCODE; -import static io.ballerina.openapi.generators.GeneratorConstants.APPLICATION_XML; -import static io.ballerina.openapi.generators.GeneratorConstants.FALSE; -import static io.ballerina.openapi.generators.GeneratorConstants.SERVICE_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.TEXT; -import static io.ballerina.openapi.generators.GeneratorConstants.TREAT_NILABLE_AS_OPTIONAL; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.convertOpenAPITypeToBallerina; -import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.GeneratorUtils.getQualifiedNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; - -/** - * This store all the util functions related service generation process. - * - * @since 2.0.0 - */ -public class ServiceGenerationUtils { - - /** - * This method will extract reference type by splitting the reference string. - * - * @param referenceVariable - Reference String - * @return Reference variable name - * @throws BallerinaOpenApiException - 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 BallerinaOpenApiException { - if (referenceVariable.startsWith("#") && referenceVariable.contains("/")) { - String[] refArray = referenceVariable.split("/"); - return escapeIdentifier(refArray[refArray.length - 1]); - } else { - throw new BallerinaOpenApiException("Invalid reference value : " + referenceVariable - + "\nBallerina only supports local reference values."); - } - } - - public static AnnotationNode getAnnotationNode(String identifier, MappingConstructorExpressionNode annotValue) { - Token atToken = createIdentifierToken("@"); - QualifiedNameReferenceNode annotReference = getQualifiedNameReferenceNode(GeneratorConstants.HTTP, identifier); - return createAnnotationNode(atToken, annotReference, annotValue); - } - - public static UnionTypeDescriptorNode getUnionNodeForOneOf(Iterator iterator) - throws BallerinaOpenApiException { - - List qualifiedNodes = new ArrayList<>(); - Token pipeToken = createIdentifierToken("|"); - while (iterator.hasNext()) { - Schema contentType = iterator.next(); - TypeDescriptorNode node = generateNodeForOASSchema(contentType); - qualifiedNodes.add((SimpleNameReferenceNode) node); - } - SimpleNameReferenceNode right = qualifiedNodes.get(qualifiedNodes.size() - 1); - SimpleNameReferenceNode traversRight = qualifiedNodes.get(qualifiedNodes.size() - 2); - UnionTypeDescriptorNode traversUnion = createUnionTypeDescriptorNode(traversRight, pipeToken, - right); - if (qualifiedNodes.size() >= 3) { - for (int i = qualifiedNodes.size() - 3; i >= 0; i--) { - traversUnion = createUnionTypeDescriptorNode(qualifiedNodes.get(i), pipeToken, - traversUnion); - } - } - return traversUnion; - } - - /** - * Generate typeDescriptor for given schema. - */ - public static TypeDescriptorNode generateNodeForOASSchema(Schema schema) throws BallerinaOpenApiException { - IdentifierToken identifierToken = createIdentifierToken(GeneratorConstants.JSON, - AbstractNodeFactory.createEmptyMinutiaeList(), SINGLE_WS_MINUTIAE); - if (schema == null) { - return createSimpleNameReferenceNode(identifierToken); - } - if (schema.get$ref() != null) { - String schemaName = getValidName(extractReferenceType(schema.get$ref()), true); - return createSimpleNameReferenceNode(createIdentifierToken(schemaName)); - } else if (schema.getType() != null) { - if (schema instanceof ArraySchema) { - TypeDescriptorNode member; - if (((ArraySchema) schema).getItems().get$ref() != null) { - member = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(getValidName(extractReferenceType(((ArraySchema) schema). - getItems().get$ref()), true))); - } else if (!(((ArraySchema) schema).getItems() instanceof ArraySchema)) { - member = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(GeneratorConstants.JSON)); - } else { - member = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken( - convertOpenAPITypeToBallerina(((ArraySchema) schema).getItems().getType()))); - } - ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( - createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - NodeList nodeList = createNodeList(dimensionNode); - return createArrayTypeDescriptorNode(member, nodeList); - } else { - identifierToken = createIdentifierToken(schema.getType(), - AbstractNodeFactory.createEmptyMinutiaeList(), SINGLE_WS_MINUTIAE); - return createSimpleNameReferenceNode(identifierToken); - } - } else if (schema instanceof ComposedSchema && (((ComposedSchema) schema).getOneOf() != null)) { - Iterator iterator = ((ComposedSchema) schema).getOneOf().iterator(); - return getUnionNodeForOneOf(iterator); - } - return createSimpleNameReferenceNode(identifierToken); - } - - /** - * Generate TypeDescriptor for all the mediaTypes. - */ - public static TypeDescriptorNode getMediaTypeToken(Map.Entry mediaType) - throws BallerinaOpenApiException { - String mediaTypeContent = mediaType.getKey().trim(); - if (mediaTypeContent.matches("text/.*")) { - mediaTypeContent = TEXT; - } - MediaType value = mediaType.getValue(); - Schema schema = value.getSchema(); - IdentifierToken identifierToken; - switch (mediaTypeContent) { - case APPLICATION_JSON: - return generateNodeForOASSchema(schema); - case APPLICATION_XML: - identifierToken = createIdentifierToken(GeneratorConstants.XML); - return createSimpleNameReferenceNode(identifierToken); - case APPLICATION_URL_ENCODE: - identifierToken = createIdentifierToken(GeneratorConstants.MAP_STRING); - return createSimpleNameReferenceNode(identifierToken); - case TEXT: - identifierToken = createIdentifierToken(GeneratorConstants.STRING); - return createSimpleNameReferenceNode(identifierToken); - case APPLICATION_OCTET_STREAM: - ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( - createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, - createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); - return createArrayTypeDescriptorNode(createBuiltinSimpleNameReferenceNode( - null, createIdentifierToken(GeneratorConstants.BYTE)), - NodeFactory.createNodeList(dimensionNode)); - default: - identifierToken = createIdentifierToken(GeneratorConstants.JSON); - return createSimpleNameReferenceNode(identifierToken); - } - } - - /** - * This util function is for generating service config annotation. - *
-     *     @http:ServiceConfig {
-     *          treatNilableAsOptional : false
-     *      }
-     * 
- */ - public static MetadataNode generateServiceConfigAnnotation() { - MetadataNode metadataNode; - BasicLiteralNode valueExpr = createBasicLiteralNode(STRING_LITERAL, - createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, FALSE, createEmptyMinutiaeList(), - createEmptyMinutiaeList())); - SpecificFieldNode fields = createSpecificFieldNode(null, - createIdentifierToken(TREAT_NILABLE_AS_OPTIONAL), createToken(COLON_TOKEN), valueExpr); - AnnotationNode annotationNode = createAnnotationNode(createToken(SyntaxKind.AT_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken(SERVICE_CONFIG, SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE)), createMappingConstructorExpressionNode( - createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(fields), - createToken(CLOSE_BRACE_TOKEN))); - metadataNode = createMetadataNode(null, createSeparatedNodeList(annotationNode)); - return metadataNode; - } - - /** - * This util function is for generating the import node for http module. - */ - public static NodeList createImportDeclarationNodes() { - List imports = new ArrayList<>(); - ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA - , GeneratorConstants.HTTP); - imports.add(importForHttp); - return AbstractNodeFactory.createNodeList(imports); - } -} diff --git a/openapi-cli/src/main/java/module-info.java b/openapi-cli/src/main/java/module-info.java index f8e22fd01..73c2e31ba 100644 --- a/openapi-cli/src/main/java/module-info.java +++ b/openapi-cli/src/main/java/module-info.java @@ -15,8 +15,6 @@ */ module io.ballerina.openapi { - requires com.fasterxml.jackson.core; - requires com.fasterxml.jackson.databind; requires handlebars; requires info.picocli; requires io.ballerina.lang; @@ -32,19 +30,11 @@ requires jsr305; requires org.apache.commons.io; requires org.slf4j; - requires swagger.core; requires swagger.parser; - requires swagger.models; requires swagger.parser.core; - requires swagger.parser.v2.converter; requires swagger.parser.v3; requires org.apache.commons.lang3; - exports io.ballerina.openapi.generators.openapi; + requires io.ballerina.openapi.core; exports io.ballerina.openapi.cmd; - exports io.ballerina.openapi.exception; - exports io.ballerina.openapi.cmd.model; - exports io.ballerina.openapi.generators.schema; - exports io.ballerina.openapi.generators.schema.model; - exports io.ballerina.openapi.generators.schema.ballerinatypegenerators; } diff --git a/openapi-cli/src/main/resources/ballerina-openapi.help b/openapi-cli/src/main/resources/ballerina-openapi.help new file mode 100644 index 000000000..304c295bd --- /dev/null +++ b/openapi-cli/src/main/resources/ballerina-openapi.help @@ -0,0 +1,126 @@ +NAME + ballerina-openapi - Generate a Ballerina service or a client from an + OpenAPI contract and vice versa. + + +SYNOPSIS + bal openapi [-i | --input] + [-o | --output] + bal openapi [-i | --input] + [-o | --output] + bal openapi [-i | --input] + [--mode ] [--tags ] + [--operations ] [-n | --nullable] + [--license] [--with-tests] + [--client-methods] + bal openapi [-i | --input] [--json] + [-s | --service] + + +DESCRIPTION + Generate a Ballerina source (either a mock service or a client stub) from + the given OpenAPI definition file or export an OpenAPI definition from a + Ballerina service. + + The generated Ballerina sources will be written into the provided output + location. + + +OPTIONS + -i, --input + This is a mandatory input. The given OpenAPI contract input will + generate a Ballerina service and the client stub files for the given + OpenAPI contract. This generated service can be used as a code + template to start the service implementation. Generated sources + contain a service definition, schema definition, and a copy of the + OpenAPI contract, which is used for the template generation. + The generated client stub is used to start the client application + implementation to call the service defined in the OpenAPI file. + The given Ballerina service file input will generate the relevant + OpenAPI specification for the service file. + + -o, --output + Location of the generated Ballerina source code. If this path is not + specified, the output will be written to the same directory from + which the command is run. + + --mode + Mode type can be 'service' or 'client'. The Ballerina service and + client will be generated according to the specified mode. + + -n, --nullable + JSON schema properties that are not marked as `nullable:true` may + return as null in some responses. It will result in a JSON schema to + Ballerina record data binding error. This is a safe option to + generate all data types in the record with Ballerina nil support. + + --license + Optional. The `.bal` files will generate with the given copyright or + license header. + + -s, --service + This service name is used to identify the service that needs to + documented as OpenApi specification. This option is used with the + command of Ballerina to OpenAPI specification generation. + + --json + Generate the Ballerina service to OpenAPI output in JSON. + The default is YAML. + + --tags + These tags are used to filter the operations tags that are needed to + generate services. This option is used with the OpenAPI to Ballerina + file generation command. + + --operations + List of operations to generate the Ballerina service or client. + + --with-tests + Work with the client generation command and generate a test + boiler-plate for all the remote functions of the generated client. + + --client-methods + This option can be used in client generation to select the client method type, which can be `resource` or `remote`. (The default option is `remote`). + +EXAMPLES + Generate a Ballerina mock service using a `hello.yaml` OpenAPI contract. + $ bal openapi -i hello.yaml --mode service + + Generate a Ballerina client using a `hello.yaml` OpenAPI contract. + $ bal openapi -i hello.yaml --mode client + + Generate a Ballerina client including boiler-plate test cases for all the + client remote functions based on the `hello.yaml` OpenAPI contract. + $ bal openapi -i hello.yaml --mode client --with-tests + + Generate both the Ballerina client and service files using a `hello.yaml` + OpenAPI contract and (optionally) write the output to the given + directory. + $ bal openapi --input hello.yaml -o ./output_path + + Generate services for the tags given in the `hello.yaml` OpenAPI + contract. + $ bal openapi -i hello.yaml --mode service --tags tag_ID + + Generate services for the operations given in the `hello.yaml` OpenAPI + contract. + $ bal openapi -i hello.yaml --mode service --operations operation_ID + + Generate all the record fields that are not specifically mentioned as + `nullable:false` in the OpenAPI schema property as nullable. + $ bal openapi -i hello.yaml --nullable + + Generate both the Ballerina client and service files including the given + license or copyright header. + $ bal openapi -i hello.yaml --license license.txt + + Generate a client with resource methods with respect to the `hello.yaml` OpenAPI contract. + $ bal openapi -i hello.yaml --client-methods resource + $ bal openapi -i hello.yaml --mode client --client-methods resource + + Export an OpenAPI definition for the `/hello` service of the + `hello_service.bal` file. + $ bal openapi -i hello_service.bal --service-name /hello + + Generate an OpenAPI specification in the JSON format. + $ bal openapi -i hello_service.bal --json diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/CodeGeneratorTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/CodeGeneratorTest.java index 1cd48de34..3c4c69fe0 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/CodeGeneratorTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/CodeGeneratorTest.java @@ -15,11 +15,13 @@ */ package io.ballerina.openapi; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.cmd.model.GenSrcFile; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.cmd.BallerinaCodeGenerator; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.ServiceGenerationUtils; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.openapi.core.model.GenSrcFile; import io.ballerina.openapi.generators.common.TestUtils; import org.apache.commons.io.FileUtils; import org.ballerinalang.formatter.core.FormatterException; @@ -38,21 +40,21 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static io.ballerina.openapi.cmd.model.GenSrcFile.GenFileType.GEN_SRC; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.TEST_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.TYPE_FILE_NAME; -import static io.ballerina.openapi.generators.GeneratorConstants.USER_DIR; -import static io.ballerina.openapi.generators.GeneratorConstants.UTIL_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.CONFIG_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.TEST_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.TYPE_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.UTIL_FILE_NAME; +import static io.ballerina.openapi.core.model.GenSrcFile.GenFileType.GEN_SRC; /** - * Unit tests for {@link CodeGenerator}. + * Unit tests for {@link BallerinaCodeGenerator}. */ public class CodeGeneratorTest { private static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); + public static final String USER_DIR = "user.dir"; Path resourcePath = Paths.get(System.getProperty(USER_DIR)); - Path expectedServiceFile = RES_DIR.resolve(Paths.get("expected_gen")); + Path expectedDirPath = RES_DIR.resolve(Paths.get("expected_gen")); List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); Filter filter = new Filter(list1, list2); @@ -61,11 +63,12 @@ public class CodeGeneratorTest { public void generateSkeleton() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("petstore.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "generateSkeleton.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "generateSkeleton.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -84,9 +87,60 @@ public void generateSkeleton() { @Test(description = "Test Ballerina client generation") public void generateClient() { String definitionPath = RES_DIR.resolve("petstore.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, "generate_client.bal"); + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "generate_client.bal"); + generator.generateClient(definitionPath, resourcePath.toString(), filter, + false, false); + if (Files.exists(resourcePath.resolve("client.bal"))) { + String generatedClient = getStringFromGivenBalFile(resourcePath, "client.bal"); + generatedClient = (generatedClient.trim()).replaceAll("\\s+", ""); + expectedClientContent = (expectedClientContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedClient.contains(expectedClientContent)); + } else { + Assert.fail("Client was not generated"); + } + } catch (IOException | BallerinaOpenApiException | FormatterException e) { + Assert.fail("Error while generating the client. " + e.getMessage()); + } finally { + deleteGeneratedFiles("client.bal"); + } + } + + @Test(description = "Test Ballerina service skeleton generation for OAS 2.0") + public void generateServiceForOAS2() { + final String serviceName = "openapipetstore"; + String definitionPath = RES_DIR.resolve("petstore_swagger.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + + try { + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, + "petstore_service_swagger.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); + if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { + String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); + generatedService = (generatedService.trim()).replaceAll("\\s+", ""); + expectedServiceContent = (expectedServiceContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedService.contains(expectedServiceContent), + "GeneratedService = " + generatedService); + } else { + Assert.fail("Service was not generated"); + } + } catch (IOException | BallerinaOpenApiException | FormatterException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles("openapipetstore_service.bal"); + } + } + + @Test(description = "Test Ballerina client generation for OAS 2.0") + public void generateClientForOAS2() { + String definitionPath = RES_DIR.resolve("petstore_swagger.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + try { + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, + "petstore_client_swagger.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, false, false); if (Files.exists(resourcePath.resolve("client.bal"))) { String generatedClient = getStringFromGivenBalFile(resourcePath, "client.bal"); @@ -135,9 +189,9 @@ public void generateDuplicatedFiles() { @Test(description = "Test Ballerina client generation with doc comments in class init function") public void generateClientWithInitDocComments() { String definitionPath = RES_DIR.resolve("x_init_description.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, "x_init_description.bal"); + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "x_init_description.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, false, false); if (Files.exists(resourcePath.resolve("client.bal"))) { @@ -158,9 +212,9 @@ public void generateClientWithInitDocComments() { @Test(description = "Test Ballerina types generation when nullable option is given") public void generateTypesWithNullableFields() { String definitionPath = RES_DIR.resolve("petstore.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, "nullable_types.bal"); + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "nullable_types.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, true, false); if (Files.exists(resourcePath.resolve("types.bal"))) { @@ -181,9 +235,9 @@ public void generateTypesWithNullableFields() { @Test(description = "Test Ballerina types generation when nullable option is given in the cmd and definition both") public void generateTypesWithNullableFieldsAndGlobalNullableTrue() { String definitionPath = RES_DIR.resolve("petstore_nullable_false.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, "nullable_false_types.bal"); + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "nullable_false_types.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, true, false); if (Files.exists(resourcePath.resolve("types.bal"))) { @@ -204,9 +258,9 @@ public void generateTypesWithNullableFieldsAndGlobalNullableTrue() { @Test(description = "Test Ballerina utils file generation") public void generateUtilsFile() { String definitionPath = RES_DIR.resolve("petstore.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, "utils.bal"); + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "utils.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, true, false); if (Files.exists(resourcePath.resolve("utils.bal"))) { @@ -227,9 +281,9 @@ public void generateUtilsFile() { @Test(description = "Test Ballerina Config.toml file generation for API Key authentication") public void generateConfigFile() { String definitionPath = RES_DIR.resolve("petstore_with_apikey_auth.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedConfigContent = getStringFromGivenBalFile(expectedServiceFile, "api_key_config.toml"); + String expectedConfigContent = getStringFromGivenBalFile(expectedDirPath, "api_key_config.toml"); generator.setIncludeTestFiles(true); generator.generateClient(definitionPath, resourcePath.toString(), filter, true, false); @@ -251,16 +305,18 @@ public void generateConfigFile() { @Test(description = "Test Ballerina client generation") public void generateFilteredClient() { String definitionPath = RES_DIR.resolve("petstore_tags.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); List listTags = new ArrayList<>(); listTags.add("pets"); listTags.add("dogs"); Filter filterCustom = new Filter(listTags, list2); try { - String expectedSchemaContent = getStringFromGivenBalFile(expectedServiceFile, + String expectedSchemaContent = getStringFromGivenBalFile(expectedDirPath, "type_filtered_by_tags.bal"); - generator.generateClient(definitionPath, resourcePath.toString(), filterCustom, false, false); - if (Files.exists(resourcePath.resolve("types.bal")) && Files.exists(resourcePath.resolve("types.bal"))) { + generator.generateClient(definitionPath, resourcePath.toString(), filterCustom, + false, false); + if (Files.exists(resourcePath.resolve("client.bal")) && + Files.exists(resourcePath.resolve("types.bal"))) { String generatedSchema = getStringFromGivenBalFile(resourcePath, "types.bal"); generatedSchema = (generatedSchema.trim()).replaceAll("\\s+", ""); expectedSchemaContent = (expectedSchemaContent.trim()).replaceAll("\\s+", ""); @@ -278,9 +334,9 @@ public void generateFilteredClient() { @Test(description = "Test Ballerina client generation with request body") public void generateClientwithRequestBody() { String definitionPath = RES_DIR.resolve("openapi-client-rb.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedClientContent = getStringFromGivenBalFile(expectedServiceFile, + String expectedClientContent = getStringFromGivenBalFile(expectedDirPath, "generate_client_requestbody.bal"); generator.generateClient(definitionPath, resourcePath.toString(), filter, false, false); @@ -303,11 +359,12 @@ public void generateClientwithRequestBody() { public void generateSkeletonForRequestbody() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("requestBody.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "generatedRB.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "generatedRB.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -328,11 +385,12 @@ public void generateSkeletonForRequestbody() { public void generateSkeletonForTwoPathParameter() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("multiPathParam.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "generated_bal.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "generated_bal.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -349,17 +407,40 @@ public void generateSkeletonForTwoPathParameter() { } } + @Test(description = "Test Ballerina client generation for catch-all path") + public void generateClientForResourceWithCatchAllPath() { + String definitionPath = RES_DIR.resolve("petstore_catch_all_path.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + try { + String expectedClientContent = getStringFromGivenBalFile( + expectedDirPath, "petstore_catch_all_path_client.bal"); + generator.generateClient(definitionPath, resourcePath.toString(), filter, false, true); + if (Files.exists(resourcePath.resolve("client.bal"))) { + String generatedClient = getStringFromGivenBalFile(resourcePath, "client.bal"); + generatedClient = (generatedClient.trim()).replaceAll("\\s+", ""); + expectedClientContent = (expectedClientContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedClient.contains(expectedClientContent)); + } else { + Assert.fail("Client was not generated"); + } + } catch (IOException | BallerinaOpenApiException | FormatterException e) { + Assert.fail("Error while generating the client. " + e.getMessage()); + } finally { + deleteGeneratedFiles("client.bal"); + } + } + @Test(description = "Test openapi definition to ballerina source code generation", - dataProvider = "fileProvider", enabled = false) + dataProvider = "fileProvider") public void openApiToBallerinaCodeGenTest(String yamlFile, String expectedFile) { String definitionPath = RES_DIR.resolve(yamlFile).toString(); Path expectedFilePath = RES_DIR.resolve(Paths.get("expected", expectedFile)); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { String expectedContent = new String(Files.readAllBytes(expectedFilePath)); List generatedFileList = generator.generateBallerinaService( - Paths.get(definitionPath), "", filter, false); + Paths.get(definitionPath), "", filter, false, false, false); if (generatedFileList.size() > 0) { GenSrcFile actualGeneratedContent = generatedFileList.get(0); Assert.assertEquals((actualGeneratedContent.getContent().trim()).replaceAll("\\s+", ""), @@ -376,11 +457,12 @@ public void openApiToBallerinaCodeGenTest(String yamlFile, String expectedFile) public void generateSkeletonForTwoQueryParameter() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("multiQueryParam.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "multi_query_para.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "multi_query_para.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -401,15 +483,16 @@ public void generateSkeletonForTwoQueryParameter() { public void generateSkeletonForTagFilter() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("petstoreTag.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); list1.add("list"); Filter filter01 = new Filter(list1, list2); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "petstoreTag.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter01, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "petstoreTag.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter01, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -430,7 +513,7 @@ public void generateSkeletonForTagFilter() { public void generateSkeletonForOperationFilter() { final String serviceName = "openapipetstore"; String definitionPath = RES_DIR.resolve("petstoreOperation.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); list1.add("list"); @@ -438,8 +521,9 @@ public void generateSkeletonForOperationFilter() { Filter filter01 = new Filter(list1, list2); try { - String expectedServiceContent = getStringFromGivenBalFile(expectedServiceFile, "petstoreOperation.bal"); - generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter01, false); + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, "petstoreOperation.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter01, + false, false, false); if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); generatedService = (generatedService.trim()).replaceAll("\\s+", ""); @@ -456,22 +540,103 @@ public void generateSkeletonForOperationFilter() { } } - @Test(description = "Test code generation when no schemas given") - public void testCodeGenerationWithoutSchemas() { + @Test(description = "Test code generation when no schemas given in service") + public void testCodeGenerationWithoutSchemasService() { + final String serviceName = "no_schema"; String definitionPath = RES_DIR.resolve("no_schema.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); try { - generator.generateClient(definitionPath, resourcePath.toString(), filter, false, false); - if (Files.exists(resourcePath.resolve("client.bal")) && - Files.notExists(resourcePath.resolve("types.bal"))) { - Assert.assertTrue(true); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), + filter, false, false, false); + boolean hasTypeFileGenerated = Files.exists(resourcePath.resolve("no_schema_service.bal")) && + Files.notExists(resourcePath.resolve("types.bal")); + Assert.assertTrue(hasTypeFileGenerated, "Empty types.bal file has been generated"); + } catch (IOException | FormatterException | BallerinaOpenApiException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles("no_schema_service.bal"); + } + } + + @Test(description = "Test Ballerina skeleton generation") + public void testGenericServiceGeneration() { + final String serviceName = "openapipetstore"; + String definitionPath = RES_DIR.resolve("petstore_original.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + + try { + String expectedServiceContent = getStringFromGivenBalFile(expectedDirPath, + "generic_service_petstore_original.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, true); + if (Files.exists(resourcePath.resolve("openapipetstore_service.bal"))) { + String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); + generatedService = (generatedService.trim()).replaceAll("\\s+", ""); + expectedServiceContent = (expectedServiceContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedService.contains(expectedServiceContent)); } else { - Assert.fail("Empty types.bal file has been generated"); + Assert.fail("Service was not generated"); } } catch (IOException | BallerinaOpenApiException | FormatterException e) { - Assert.fail("Error while generating the client. " + e.getMessage()); + Assert.fail("Error while generating the service. " + e.getMessage()); } finally { - deleteGeneratedFiles("client.bal"); + deleteGeneratedFiles("openapipetstore_service.bal"); + } + } + + @Test(description = "Test code generation for no schema in given contract but user created type available in " + + "service") + public void testForGeneratingTypeFileWhenNoSchema() { + final String serviceName = "no_schema"; + String definitionPath = RES_DIR.resolve("no_schema_with_type_bal.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + try { + generator.generateService(definitionPath, serviceName, resourcePath.toString(), + filter, false, false, false); + boolean hasTypeFileGenerated = Files.exists(resourcePath.resolve("no_schema_service.bal")) && + Files.exists(resourcePath.resolve("types.bal")); + Assert.assertTrue(hasTypeFileGenerated, "types.bal file has not been generated"); + } catch (IOException | BallerinaOpenApiException | FormatterException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles("no_schema_service.bal"); + } + } + + @Test(description = "Test service generation for request and responses with wildcard media type") + public void testServiceGenerationWhenWildCardMediaTypeGiven() { + final String serviceName = "openapipetstore"; + String definitionPath = RES_DIR.resolve("petstore_wildcard.yaml").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + + try { + String expectedServiceContent = getStringFromGivenBalFile( + expectedDirPath, "petstore_wildcard_service.bal"); + String expectedTypesContent = getStringFromGivenBalFile( + expectedDirPath, "petstore_wildcard_types.bal"); + generator.generateService(definitionPath, serviceName, resourcePath.toString(), filter, + false, false, false); + if (Files.exists(resourcePath.resolve("openapipetstore_service.bal")) && + Files.exists(resourcePath.resolve("types.bal"))) { + String generatedService = getStringFromGivenBalFile(resourcePath, "openapipetstore_service.bal"); + generatedService = (generatedService.trim()).replaceAll("\\s+", ""); + expectedServiceContent = (expectedServiceContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedService.contains(expectedServiceContent), + "Expected service and actual generated service is not matching"); + + String generatedTypes = getStringFromGivenBalFile(resourcePath, "types.bal"); + generatedTypes = (generatedTypes.trim()).replaceAll("\\s+", ""); + expectedTypesContent = (expectedTypesContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedTypes.contains(expectedTypesContent), + "Expected types and actual generated types are not matching"); + + } else { + Assert.fail("Service was not generated"); + } + } catch (IOException | BallerinaOpenApiException | FormatterException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles("openapipetstore_service.bal"); } } @@ -481,7 +646,18 @@ public void testCodeGenerationWithoutSchemas() { public void testForInvalidDefinition() throws IOException, BallerinaOpenApiException, FormatterException { String definitionPath = RES_DIR.resolve("invalid_petstore.yaml").toString(); - CodeGenerator generator = new CodeGenerator(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); + generator.generateClient(definitionPath, "", filter, false, false); + } + + @Test(description = "Functionality tests when swagger 1.2 contract is given as input", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Provided OpenAPI contract version is not supported in the tool. " + + "Use OpenAPI specification version 2 or higher") + public void testGenerationForUnsupportedOpenAPIVersion() throws IOException, BallerinaOpenApiException, + FormatterException { + String definitionPath = RES_DIR.resolve("petstore_swagger_1.2.json").toString(); + BallerinaCodeGenerator generator = new BallerinaCodeGenerator(); generator.generateClient(definitionPath, "", filter, false, false); } @@ -490,11 +666,25 @@ public void escapeIdentifierTest() { Assert.assertEquals(GeneratorUtils.escapeIdentifier("abc"), "abc"); Assert.assertEquals(GeneratorUtils.escapeIdentifier("string"), "'string"); Assert.assertEquals(GeneratorUtils.escapeIdentifier("int"), "'int"); - Assert.assertEquals(GeneratorUtils.escapeIdentifier("io.foo.bar"), "'io\\.foo\\.bar"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("io.foo.bar"), "io\\.foo\\.bar"); Assert.assertEquals(GeneratorUtils.escapeIdentifier("getV1CoreVersion"), "getV1CoreVersion"); - Assert.assertEquals(GeneratorUtils.escapeIdentifier("org-invitation"), "'org\\-invitation"); - Assert.assertEquals(GeneratorUtils.escapeIdentifier("int?"), "'int\\?"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("org-invitation"), "org\\-invitation"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("int?"), "int\\?"); Assert.assertEquals(GeneratorUtils.escapeIdentifier("error"), "'error"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("foo_bar$_baz"), "foo_bar\\$_baz"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("foo_bar_baz"), "foo_bar_baz"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("foo'baz"), "foo\\'baz"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("200"), "'200"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("2023-06-28"), "'2023\\-06\\-28"); + Assert.assertEquals(GeneratorUtils.escapeIdentifier("3h"), "'3h"); + } + + @Test + public void testForSelectMediaType() { + Assert.assertEquals(ServiceGenerationUtils.selectMediaType("text/json"), + GeneratorConstants.APPLICATION_JSON); + Assert.assertEquals(ServiceGenerationUtils.selectMediaType("text/xml"), + GeneratorConstants.APPLICATION_XML); } private String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { @@ -527,6 +717,7 @@ public Object[][] fileProvider() { {"multiMethodResources.yaml", "multiMethodResources.bal"}, {"nonEmptyPath.yaml", "nonEmptyPath.bal"}, {"petstore.yaml", "petstore.bal"}, + {"petstore_catch_all_path.yaml", "petstore_catch_all_path.bal"} }; } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/cmd/BallerinaCodeGeneratorLicenseTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/BallerinaCodeGeneratorLicenseTests.java new file mode 100644 index 000000000..79db8e848 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/BallerinaCodeGeneratorLicenseTests.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * 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.openapi.cmd; + +import org.apache.commons.io.FileUtils; +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.File; +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; + +/** + * OpenAPI to Ballerina command tests for check license headers. + */ +public class BallerinaCodeGeneratorLicenseTests extends OpenAPICommandTest { + + private static final String LINE_SEPARATOR = System.lineSeparator(); + + @BeforeTest(description = "This will create a new ballerina project for testing below scenarios.") + public void setupBallerinaProject() throws IOException { + super.setup(); + } + + @Test(description = "Test openapi to ballerina client generation with default file headers") + public void testClientGeneration() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--mode", "client"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("utils.bal")) && + Files.exists(this.tmpDir.resolve("types.bal"))) { + try { + compareFiles("schema.bal", "types.bal"); + compareFiles("client.bal", "client.bal"); + compareFiles("utils_for_client_generation.bal", "utils.bal"); + deleteGeneratedFiles(false); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + } else { + Assert.fail("Code generation failed. : " + readOutput(true)); + } + } + + @Test(description = "Test openapi to ballerina service type generation with default file headers") + public void testServiceTypeGeneration() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--with-service-type"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("utils.bal")) && + Files.exists(this.tmpDir.resolve("types.bal")) && + Files.exists(this.tmpDir.resolve("service_type.bal"))) { + try { + compareFiles("schema_for_both_service_client.bal", "types.bal"); + compareFiles("client.bal", "client.bal"); + compareFiles("utils_for_both_service_client_generation.bal", "utils.bal"); + compareFiles("service_type.bal", "service_type.bal"); + deleteGeneratedFiles(false); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + } else { + Assert.fail("Code generation failed. : " + readOutput(true)); + } + } + + @Test(description = "Test openapi to ballerina service generation with default file headers") + public void testServiceGeneration() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--with-service-type", + "--mode", "service"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + + if (Files.exists(this.tmpDir.resolve("petstore_service.bal")) && + Files.exists(this.tmpDir.resolve("types.bal")) && + Files.exists(this.tmpDir.resolve("service_type.bal"))) { + try { + compareFiles("schema_for_service.bal", "types.bal"); + compareFiles("service_with_service_type.bal", "petstore_service.bal"); + compareFiles("service_type.bal", "service_type.bal"); + deleteGeneratedFiles(false); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + } else { + Assert.fail("Code generation failed. : " + readOutput(true)); + } + } + + @Test(description = "Test openapi to ballerina code generation with default file headers") + public void testBothClientServiceGeneration() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString()}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("utils.bal")) && + Files.exists(this.tmpDir.resolve("types.bal")) && + Files.exists(this.tmpDir.resolve("petstore_service.bal"))) { + try { + compareFiles("types_for_both_service_client_generations.bal", "types.bal"); + compareFiles("client.bal", "client.bal"); + compareFiles("utils_for_both_service_client_generation.bal", "utils.bal"); + compareFiles("service.bal", "petstore_service.bal"); + deleteGeneratedFiles(false); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + } else { + Assert.fail("Code generation failed. : " + readOutput(true)); + } + } + + @Test(description = "Test openapi to ballerina code generation with user provided license headers") + public void testUserGivenLicenseHeader() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + Path licenseHeader = resourceDir.resolve(Paths.get("expected_gen/licenses/license.txt")); + String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--license", + licenseHeader.toString(), "--with-service-type"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("utils.bal")) && + Files.exists(this.tmpDir.resolve("types.bal")) && + Files.exists(this.tmpDir.resolve("service_type.bal")) && + Files.exists(this.tmpDir.resolve("petstore_service.bal"))) { + try { + compareFiles("schema_with_user_given_license.bal", "types.bal"); + compareFiles("client_with_user_given_license.bal", "client.bal"); + compareFiles("utils_for_with_user_given_license.bal", "utils.bal"); + compareFiles("service_type_with_user_given_license.bal", "service_type.bal"); + compareFiles("service_with_user_given_license.bal", "petstore_service.bal"); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } finally { + deleteGeneratedFiles(true); + } + } else { + Assert.fail("Code generation failed. : " + readOutput(true)); + } + } + + /** + * Compare two files. + */ + private void compareFiles(String expectedFileName, String generatedFileName) throws IOException { + Stream expectedFile = Files.lines(resourceDir.resolve(Paths.get("expected_gen/licenses", + expectedFileName))); + String expectedContent = expectedFile.collect(Collectors.joining(LINE_SEPARATOR)); + Stream generatedFile = Files.lines(this.tmpDir.resolve(generatedFileName)); + String generatedContent = generatedFile.collect(Collectors.joining(LINE_SEPARATOR)); + generatedContent = generatedContent.trim().replaceAll("\\s+", ""); + expectedContent = expectedContent.trim().replaceAll("\\s+", ""); + Assert.assertEquals(generatedContent, expectedContent); + } + + // Delete the generated files + private void deleteGeneratedFiles(boolean isConfigGenerated) throws IOException { + File serviceFile = new File(this.tmpDir.resolve("petstore_service.bal").toString()); + File clientFile = new File(this.tmpDir.resolve("client.bal").toString()); + File schemaFile = new File(this.tmpDir.resolve("types.bal").toString()); + File testFile = new File(this.tmpDir.resolve("tests/test.bal").toString()); + File testDir = new File(this.tmpDir.resolve("tests").toString()); + serviceFile.delete(); + clientFile.delete(); + schemaFile.delete(); + testFile.delete(); + if (isConfigGenerated) { + File configFile = new File(this.tmpDir.resolve("tests/Config.toml").toString()); + configFile.delete(); + } + FileUtils.deleteDirectory(testDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenAPICmdTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenAPICmdTest.java index 0973a5aef..728c4f8f4 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenAPICmdTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenAPICmdTest.java @@ -18,7 +18,10 @@ package io.ballerina.openapi.cmd; import io.ballerina.cli.launcher.BLauncherException; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.generators.common.TestUtils; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import org.apache.commons.io.FileUtils; import org.testng.Assert; import org.testng.annotations.AfterTest; @@ -38,6 +41,7 @@ * OpenAPI command test suit. */ public class OpenAPICmdTest extends OpenAPICommandTest { + private static final String LINE_SEPARATOR = System.lineSeparator(); @BeforeTest(description = "This will create a new ballerina project for testing below scenarios.") @@ -56,6 +60,17 @@ public void testOpenAPICmdHelp() throws IOException { " ballerina-openapi - Generate a Ballerina service")); } + @Test(description = "Test openapi command with help flag") + public void testOpenAPICmdHelpWithBalTools() throws IOException { + String[] args = {"help", "openapi"}; + OpenApiCmd openApiCommand = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(openApiCommand).parseArgs(args); + openApiCommand.execute(); + String output = readOutput(true); + Assert.assertTrue(output.contains("NAME\n" + + " ballerina-openapi - Generate a Ballerina service")); + } + @Test(description = "Test openapi command without help flag") public void testOpenAPICmdHelpWithoutFlag() throws IOException { OpenApiCmd openApiCommand = new OpenApiCmd(printStream, tmpDir, false); @@ -73,7 +88,7 @@ public void testWithoutOpenApiContract() throws IOException { new CommandLine(cmd).parseArgs(args); cmd.execute(); String output = readOutput(true); - Assert.assertTrue(output.contains("An OpenAPI definition file is required to generate the service.")); + Assert.assertTrue(output.contains("An OpenAPI definition path is required to generate the service.")); } @Test(description = "Test openapi gen-service for successful service generation") @@ -154,6 +169,76 @@ public void testSuccessfulTypeBalGeneration() throws IOException { } } + @Test + public void testForRemovedUnusedConstraintImport() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("non_constraint_import.yaml")); + String[] args = {"--input", petstoreYaml.toString(), + "--mode", "client", "--tags", "pets", "-o", this.tmpDir.toString()}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + Path expectedSchemaFile = resourceDir.resolve(Paths.get("expected_gen", + "non_constraint_import_types.bal")); + String expectedSchemaContent = ""; + try (Stream expectedSchemaLines = Files.lines(expectedSchemaFile)) { + expectedSchemaContent = expectedSchemaLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("types.bal"))) { + //Compare schema contents + String generatedSchema = ""; + try (Stream generatedSchemaLines = Files.lines(this.tmpDir.resolve("types.bal"))) { + generatedSchema = generatedSchemaLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + generatedSchema = (generatedSchema.trim()).replaceAll("\\s+", ""); + expectedSchemaContent = (expectedSchemaContent.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedSchema, expectedSchemaContent, + "Expected content and actual generated content is mismatched for: " + petstoreYaml); + deleteGeneratedFiles(false); + } else { + Assert.fail("Type generation failed. : " + readOutput(true)); + } + } + + @Test(description = "This test for checking the constraint import when the type uses the constraint") + public void testWithConstraintImport() throws IOException { + Path petstoreYaml = resourceDir.resolve(Paths.get("constraint_import.yaml")); + String[] args = {"--input", petstoreYaml.toString(), + "--mode", "client", "--tags", "pets", "-o", this.tmpDir.toString()}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + Path expectedSchemaFile = resourceDir.resolve(Paths.get("expected_gen", + "constraint_import_types.bal")); + String expectedSchemaContent = ""; + try (Stream expectedSchemaLines = Files.lines(expectedSchemaFile)) { + expectedSchemaContent = expectedSchemaLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + if (Files.exists(this.tmpDir.resolve("client.bal")) && + Files.exists(this.tmpDir.resolve("types.bal"))) { + //Compare schema contents + String generatedSchema = ""; + try (Stream generatedSchemaLines = Files.lines(this.tmpDir.resolve("types.bal"))) { + generatedSchema = generatedSchemaLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + generatedSchema = (generatedSchema.trim()).replaceAll("\\s+", ""); + expectedSchemaContent = (expectedSchemaContent.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedSchema, expectedSchemaContent, + "Expected content and actual generated content is mismatched for: " + petstoreYaml); + deleteGeneratedFiles(false); + } else { + Assert.fail("Type generation failed. : " + readOutput(true)); + } + } + @Test(description = "Test openapi to ballerina generation with license headers") public void testGenerationWithLicenseHeaders() throws IOException { Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); @@ -242,7 +327,7 @@ public void testGenerationWithLicenseHeadersWithOneNewLine() throws IOException public void testConnectorGenerationFilteringByTags() throws IOException { Path petstoreYaml = resourceDir.resolve(Paths.get("petstore_tags.yaml")); String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--tags", - "pets,dogs", "--mode", "client"}; + "pets,dogs", "--mode", "client", "--client-methods", "remote"}; OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); new CommandLine(cmd).parseArgs(args); cmd.execute(); @@ -337,7 +422,7 @@ public void testInvalidPrefixFile() throws IOException, BallerinaOpenApiExceptio } @Test(description = "Test generation without including test files") - public void testClientGenerationWithoutIncludeTestFilesOption() throws IOException, BallerinaOpenApiException { + public void testClientGenerationWithoutIncludeTestFilesOption() throws IOException { Path petstoreYaml = resourceDir.resolve(Paths.get("petstore_with_oauth.yaml")); Path licenseHeader = resourceDir.resolve(Paths.get("license.txt")); String[] args = {"--input", petstoreYaml.toString(), "-o", this.tmpDir.toString(), "--license", @@ -359,8 +444,8 @@ public void testClientGenerationWithoutIncludeTestFilesOption() throws IOExcepti !Files.exists(this.tmpDir.resolve("tests/Config.toml")) && !Files.exists(this.tmpDir.resolve("tests/test.bal"))) { - Assert.assertTrue(true); - deleteGeneratedFiles(true); + Assert.assertTrue(true); + deleteGeneratedFiles(true); } else { Assert.fail("Code generation failed. : " + readOutput(true)); } @@ -408,6 +493,86 @@ public void testSuccessfulServiceGenerationForYML() throws IOException { } } + @Test(description = "Test Ballerina service generation with service type") + public void testServiceTypeGeneration() throws IOException { + Path projectDir = resourceDir.resolve("expected_gen").resolve("ballerina_project"); + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", projectDir.toString(), "--with-service-type"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + Path expectedServiceTypeFile = resourceDir.resolve(Paths.get("expected_gen", "pestore_service_type.bal")); + String expectedServiceTypeContent = ""; + try (Stream expectedServiceTypeLines = Files.lines(expectedServiceTypeFile)) { + expectedServiceTypeContent = expectedServiceTypeLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + if (Files.exists(projectDir.resolve("client.bal")) && + Files.exists(projectDir.resolve("petstore_service.bal")) && + Files.exists(projectDir.resolve("types.bal")) && + Files.exists(projectDir.resolve("service_type.bal"))) { + //Compare schema contents + String generatedServiceType = ""; + try (Stream generatedServiceTypeLines = Files.lines(projectDir.resolve("service_type.bal"))) { + generatedServiceType = generatedServiceTypeLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + generatedServiceType = (generatedServiceType.trim()).replaceAll("\\s+", ""); + expectedServiceTypeContent = (expectedServiceTypeContent.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedServiceType, expectedServiceTypeContent, + "Expected content and actual generated content is mismatched for: " + petstoreYaml.toString()); + } else { + Assert.fail("Service generation failed. : " + readOutput(true)); + } + } + + @Test(description = "Test Ballerina service generation without data binding") + public void testServiceGenerationWithoutDataBinding() throws IOException { + Path projectDir = resourceDir.resolve("expected_gen").resolve("ballerina_project"); + Path petstoreYaml = resourceDir.resolve(Paths.get("petstore.yaml")); + String[] args = {"--input", petstoreYaml.toString(), "-o", projectDir.toString(), "--without-data-binding"}; + OpenApiCmd cmd = new OpenApiCmd(printStream, tmpDir, false); + new CommandLine(cmd).parseArgs(args); + cmd.execute(); + Path expectedService = resourceDir.resolve(Paths.get("expected_gen", "generic_service_petstore.bal")); + String expectedServiceContent = ""; + try (Stream expectedServiceTypeLines = Files.lines(expectedService)) { + expectedServiceContent = expectedServiceTypeLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + if (Files.exists(projectDir.resolve("client.bal")) && + Files.exists(projectDir.resolve("petstore_service.bal")) && + Files.exists(projectDir.resolve("types.bal"))) { + //Compare schema contents + String generatedService = ""; + try (Stream generatedServiceLines = Files.lines(projectDir.resolve("petstore_service.bal"))) { + generatedService = generatedServiceLines.collect(Collectors.joining(LINE_SEPARATOR)); + } catch (IOException e) { + Assert.fail(e.getMessage()); + } + generatedService = (generatedService.trim()).replaceAll("\\s+", ""); + expectedServiceContent = (expectedServiceContent.trim()).replaceAll("\\s+", ""); + if (expectedServiceContent.equals(generatedService)) { + SemanticModel semanticModel = TestUtils.getSemanticModel( + projectDir.resolve("petstore_service.bal")); + boolean hasErrors = semanticModel.diagnostics().stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors, "Errors found in generated service"); + deleteGeneratedFiles(false, projectDir, true); + } else { + Assert.fail("Expected content and actual generated content is mismatched for: " + + petstoreYaml.toString()); + deleteGeneratedFiles(false, projectDir, true); + } + } else { + Assert.fail("Service generation failed. : " + readOutput(true)); + } + + } + @Test(description = "Test for service generation with yaml contract without operationID") public void testForYamlContractWithoutOperationID() throws IOException { Path yamlContract = resourceDir.resolve(Paths.get("without_operationID.yaml")); @@ -444,6 +609,29 @@ private void deleteGeneratedFiles(boolean isConfigGenerated) throws IOException FileUtils.deleteDirectory(testDir); } + private void deleteGeneratedFiles(boolean isConfigGenerated, Path folderPath, boolean isServiceTypeGenerated) + throws IOException { + File serviceFile = new File(folderPath.resolve("petstore_service.bal").toString()); + File clientFile = new File(folderPath.resolve("client.bal").toString()); + File schemaFile = new File(folderPath.resolve("types.bal").toString()); + File testFile = new File(folderPath.resolve("tests/test.bal").toString()); + File testDir = new File(folderPath.resolve("tests").toString()); + serviceFile.delete(); + clientFile.delete(); + schemaFile.delete(); + testFile.delete(); + if (isConfigGenerated) { + File configFile = new File(folderPath.resolve("tests/Config.toml").toString()); + configFile.delete(); + } + if (isServiceTypeGenerated) { + File serviceTypeFile = new File(folderPath.resolve("service_type.bal").toString()); + File utilFile = new File(folderPath.resolve("utils.bal").toString()); + utilFile.delete(); + } + FileUtils.deleteDirectory(testDir); + } + @Test(description = "getRelative path") public void getRelativePath() { OpenApiCmd cmd = new OpenApiCmd(); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenApiGenServiceCmdTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenApiGenServiceCmdTest.java index 451396689..c8765cfab 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenApiGenServiceCmdTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/cmd/OpenApiGenServiceCmdTest.java @@ -27,7 +27,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static io.ballerina.openapi.generators.GeneratorConstants.USER_DIR; +import static io.ballerina.openapi.CodeGeneratorTest.USER_DIR; /** * This class contains tests necessary to test OpenApi Generate Service command. diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/ApiKeyAuthTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/ApiKeyAuthTests.java index 3e2df0d48..b1bc7f42f 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/ApiKeyAuthTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/ApiKeyAuthTests.java @@ -19,11 +19,13 @@ package io.ballerina.openapi.generators.auth; import io.ballerina.compiler.syntax.tree.Node; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; import io.ballerina.openapi.generators.common.TestConstants; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.security.SecurityScheme; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -32,23 +34,52 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Optional; /** * All the tests related to the auth related code snippet generation for api key auth mechanism. */ public class ApiKeyAuthTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/client/").toAbsolutePath(); - BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(true, false); + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + true, false); - @Test(description = "Generate config record for openweathermap api", dataProvider = "apiKeyAuthIOProvider") + @Test(description = "Generate ConnectionConfig record for openweathermap api", + dataProvider = "apiKeyAuthIOProvider") public void testGetConfigRecord(String yamlFile) throws IOException, BallerinaOpenApiException { - // generate ApiKeysConfig record Path definitionPath = RES_DIR.resolve("auth/scenarios/api_key/" + yamlFile); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); - Assert.assertFalse(generatedConfigRecord.isBlank()); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); + List authRelatedTypeDefinitionNodes = + ballerinaAuthConfigGenerator.getAuthRelatedTypeDefinitionNodes(); + Optional connectionConfig = authRelatedTypeDefinitionNodes.stream() + .filter(typeDefinitionNode -> typeDefinitionNode.typeName().text().equals("ConnectionConfig")) + .findFirst(); + if (connectionConfig.isPresent()) { + String expectedRecord = TestConstants.CONNECTION_CONFIG_NO_AUTH; + String generatedRecord = connectionConfig.get().toString(); + generatedRecord = (generatedRecord.trim()).replaceAll("\\s+", ""); + expectedRecord = (expectedRecord.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedRecord, expectedRecord); + } else { + Assert.fail(); + } + } + + @Test(description = "Generate ConnectionConfig record for openweathermap api", + dataProvider = "apiKeyAuthIOProvider") + public void testGetApiKeysConfigRecord(String yamlFile) throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("auth/scenarios/api_key/" + yamlFile); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); + List authRelatedTypeDefinitionNodes = + ballerinaAuthConfigGenerator.getAuthRelatedTypeDefinitionNodes(); + Optional apiKeysConfig = authRelatedTypeDefinitionNodes.stream() + .filter(typeDefinitionNode -> typeDefinitionNode.typeName().text().equals("ApiKeysConfig")) + .findFirst(); + Assert.assertTrue(apiKeysConfig.isPresent()); } @Test(description = "Test the generation of ApiKey map local variable", @@ -89,12 +120,15 @@ public void testGetApiKeyAssignmentNode () { @Test(description = "Test the generation of api key documentation comment when multiple api keys defined") public void testGetApiKeyDescriptionForMultipleApiKeys () throws IOException, BallerinaOpenApiException { - BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(true, false); + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + true, false); Path definitionPath = RES_DIR.resolve("auth/scenarios/api_key/multiple_apikey_descriptions.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + ballerinaAuthConfigGenerator.setAuthTypes(securitySchemeMap); String expectedConfigRecord = TestConstants.MULTIPLE_API_KEY_RECORD; String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); + ballerinaAuthConfigGenerator.generateApiKeysConfig()).toString(); generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); Assert.assertEquals(generatedConfigRecord, expectedConfigRecord); @@ -103,12 +137,15 @@ public void testGetApiKeyDescriptionForMultipleApiKeys () throws IOException, Ba @Test(description = "Test ApiKeysConfig record generation for multiple api keys") public void testConfigRecordGenForAPIKeyAuth() throws IOException, BallerinaOpenApiException { // generate ApiKeysConfig record - BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(true, false); + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + true, false); String expectedConfigRecord = TestConstants.API_KEYS_CONFIG_RECORD; Path definitionPath = RES_DIR.resolve("auth/scenarios/api_key/multiple_api_keys.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + ballerinaAuthConfigGenerator.setAuthTypes(securitySchemeMap); String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); + ballerinaAuthConfigGenerator.generateApiKeysConfig()).toString(); Assert.assertFalse(generatedConfigRecord.isBlank()); generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); @@ -118,12 +155,15 @@ public void testConfigRecordGenForAPIKeyAuth() throws IOException, BallerinaOpen @Test(description = "Test ApiKeysConfig record documentation generation for multiline descriptions") public void testConfigRecordDocumentationGen() throws IOException, BallerinaOpenApiException { // generate ApiKeysConfig record - BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(true, false); + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + true, false); String expectedConfigRecord = TestConstants.MULTI_LINE_API_KEY_DESC; Path definitionPath = RES_DIR.resolve("auth/scenarios/api_key/multiline_api_key_desc.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + ballerinaAuthConfigGenerator.setAuthTypes(securitySchemeMap); String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); + ballerinaAuthConfigGenerator.generateApiKeysConfig()).toString(); Assert.assertFalse(generatedConfigRecord.isBlank()); generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpAuthTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpAuthTests.java index 6c3b9011c..8f9ce01ab 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpAuthTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpAuthTests.java @@ -20,11 +20,12 @@ import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; import io.ballerina.openapi.generators.common.TestConstants; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.security.SecurityScheme; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -33,6 +34,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.Map; import java.util.Objects; /** @@ -44,13 +46,15 @@ public class HttpAuthTests { @Test(description = "Generate config record for http basic auth", dataProvider = "httpAuthIOProvider") public void testGetConfigRecord(String yamlFile, String configRecord) throws IOException, BallerinaOpenApiException { - Path definitionPath = RES_DIR.resolve("scenarios/http/" + yamlFile); BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( false, true); + Path definitionPath = RES_DIR.resolve("scenarios/http/" + yamlFile); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + ballerinaAuthConfigGenerator.setAuthTypes(securitySchemeMap); String expectedConfigRecord = configRecord; String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); + ballerinaAuthConfigGenerator.generateConnectionConfigRecord()).toString(); generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); Assert.assertEquals(expectedConfigRecord, generatedConfigRecord); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpConfigurationExtensionTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpConfigurationExtensionTests.java new file mode 100644 index 000000000..6dec56643 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/HttpConfigurationExtensionTests.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.generators.auth; + +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.openapi.generators.common.TestConstants; +import io.swagger.v3.oas.models.OpenAPI; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; + +/** + * This class contains all the tests related to the ConnectionConfig record generation when + * x-ballerina-http-config is defined. + */ +public class HttpConfigurationExtensionTests { + private static final Path RES_DIR = Paths.get("src/test/resources/generators/client/auth").toAbsolutePath(); + + @Test(description = "Generate config record when http version is given") + public void testGetConfigRecordGeneration() throws IOException, BallerinaOpenApiException { + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + false, false); + Path definitionPath = RES_DIR.resolve("scenarios/http_config_extension/petstore_with_http_version.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); + String expectedConfigRecord = TestConstants.CONNECTION_CONFIG_HTTP_VERSION_1_1; + String generatedConfigRecord = Objects.requireNonNull( + ballerinaAuthConfigGenerator.generateConnectionConfigRecord()).toString(); + generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); + expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(expectedConfigRecord, generatedConfigRecord); + } + + @Test(description = "Generate config record when invalid http version is given") + public void testGetConfigRecordGenerationForInvalidHTTPVersion() throws IOException, BallerinaOpenApiException { + BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( + false, false); + Path definitionPath = RES_DIR.resolve( + "scenarios/http_config_extension/petstore_with_invalid_http_version.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); + String expectedConfigRecord = TestConstants.CONNECTION_CONFIG_NO_AUTH; + String generatedConfigRecord = Objects.requireNonNull( + ballerinaAuthConfigGenerator.generateConnectionConfigRecord()).toString(); + generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); + expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(expectedConfigRecord, generatedConfigRecord); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/MixedApiKeyAndHTTPAuthTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/MixedApiKeyAndHTTPAuthTests.java index c803c2963..a1c073f03 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/MixedApiKeyAndHTTPAuthTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/MixedApiKeyAndHTTPAuthTests.java @@ -19,9 +19,10 @@ package io.ballerina.openapi.generators.auth; import io.ballerina.compiler.syntax.tree.Node; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; import io.ballerina.openapi.generators.common.TestConstants; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; @@ -32,7 +33,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import java.util.Objects; +import java.util.Optional; /** * All the tests related to the auth related code snippet generation for api key auth mechanism. @@ -45,17 +46,21 @@ public class MixedApiKeyAndHTTPAuthTests { public void testGetConfigRecord(String yamlFile) throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/" + yamlFile); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); - Assert.assertFalse(generatedConfigRecord.isBlank()); - } - - @Test(description = "Generate AuthConfig record") - public void testGetAuthConfigRecord() { - String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getAuthConfigRecord()).toString(); - Assert.assertTrue(generatedConfigRecord.contains(TestConstants.authConfigRecordDoc)); - Assert.assertTrue(generatedConfigRecord.contains("|ApiKeysConfigauth;")); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); + List authRelatedTypeDefinitionNodes = + ballerinaAuthConfigGenerator.getAuthRelatedTypeDefinitionNodes(); + Optional connectionConfig = authRelatedTypeDefinitionNodes.stream() + .filter(typeDefinitionNode -> typeDefinitionNode.typeName().text().equals("ConnectionConfig")) + .findFirst(); + if (connectionConfig.isPresent()) { + String expectedRecord = TestConstants.CONNECTION_CONFIG_MIXED_AUTH; + String generatedRecord = connectionConfig.get().toString(); + generatedRecord = (generatedRecord.trim()).replaceAll("\\s+", ""); + expectedRecord = (expectedRecord.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedRecord, expectedRecord); + } else { + Assert.fail(); + } } @Test(description = "Test the generation of nillable ApiKeysConfig class variable", diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/OAuth2Tests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/OAuth2Tests.java index f3ac3c7cb..0896670bd 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/OAuth2Tests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/auth/OAuth2Tests.java @@ -20,11 +20,12 @@ import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; import io.ballerina.openapi.generators.common.TestConstants; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.security.SecurityScheme; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -33,6 +34,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.Map; import java.util.Objects; /** @@ -49,9 +51,11 @@ public void testGetConfigRecord(String yamlFile, String configRecord) throws IOE true); Path definitionPath = RES_DIR.resolve("scenarios/oauth2/" + yamlFile); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + ballerinaAuthConfigGenerator.setAuthTypes(securitySchemeMap); String expectedConfigRecord = configRecord; String generatedConfigRecord = Objects.requireNonNull( - ballerinaAuthConfigGenerator.getConfigRecord(openAPI)).toString(); + ballerinaAuthConfigGenerator.generateConnectionConfigRecord()).toString(); generatedConfigRecord = (generatedConfigRecord.trim()).replaceAll("\\s+", ""); expectedConfigRecord = (expectedConfigRecord.trim()).replaceAll("\\s+", ""); Assert.assertEquals(expectedConfigRecord, generatedConfigRecord); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AllOfResponsesTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AllOfResponsesTests.java index a0296caff..9b6390a2c 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AllOfResponsesTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AllOfResponsesTests.java @@ -18,8 +18,9 @@ package io.ballerina.openapi.generators.client; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.FunctionReturnTypeGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.Test; @@ -33,7 +34,7 @@ /** * All the tests related to the functionSignatureNode Return type tests in - * {@link BallerinaClientGenerator} util. + * {@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator} util. */ public class AllOfResponsesTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); @@ -45,7 +46,7 @@ public void getReturnTypeTests() throws IOException, BallerinaOpenApiException { FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(response, ballerinaSchemaGenerator, new ArrayList<>()); Assert.assertEquals(functionReturnType.getReturnType(response.getPaths().get("/products").getGet(), - true), "CompoundTestsProductsResponse|error"); + true), "Inline_response_200|error"); } @Test(description = "Tests for returnType") public void getReturnTypeForAllOf() throws IOException, BallerinaOpenApiException { @@ -54,7 +55,7 @@ public void getReturnTypeForAllOf() throws IOException, BallerinaOpenApiExceptio FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(response, ballerinaSchemaGenerator, new ArrayList<>()); Assert.assertEquals(functionReturnType.getReturnType(response.getPaths().get("/users/{userId}/meetings") - .getPost(), true), "CompoundCreateMeetingResponse|error"); + .getPost(), true), "Inline_response_201|error"); } @Test(description = "Tests for the object response without property") public void getReturnTypeForObjectSchema() throws IOException, BallerinaOpenApiException { @@ -79,7 +80,7 @@ public void getReturnTypeForMapSchema() throws IOException, BallerinaOpenApiExce String returnType = functionReturnType.getReturnType(response.getPaths().get("/products").getGet(), true); - Assert.assertEquals(returnType, "TestsProductsResponse|error"); + Assert.assertEquals(returnType, "Inline_response_200|error"); } @Test(description = "Tests for the object response without property and without additional properties") @@ -105,7 +106,7 @@ public void getReturnTypeForMapSchemaWithOutAdditionalProperties() throws IOExce String returnType = functionReturnType.getReturnType(response.getPaths().get("/products").getGet(), true); - Assert.assertEquals(returnType, "TestsProductsResponse|error"); + Assert.assertEquals(returnType, "Inline_response_200|error"); } // 1. nested allof // 2. allof with reference diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AnnotationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AnnotationTests.java index 4ce3b29f0..94304ff37 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AnnotationTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/AnnotationTests.java @@ -21,10 +21,12 @@ import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.DocCommentsGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -42,7 +44,7 @@ /** * All the tests related to the Display Annotation in the generated code related to the - * {@link BallerinaClientGenerator} + * {{@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} * util. */ public class AnnotationTests { @@ -96,9 +98,13 @@ public void openApiToBallerinaClientGenWithAnnotation(String yamlFile, String e List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); Filter filter = new Filter(list1, list2); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/BallerinaDiagnosticTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/BallerinaDiagnosticTests.java index de09e9f8e..bcd5c06bb 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/BallerinaDiagnosticTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/BallerinaDiagnosticTests.java @@ -19,12 +19,15 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.openapi.generators.common.TestUtils; import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.SpecVersion; import org.ballerinalang.formatter.core.FormatterException; import org.testng.Assert; import org.testng.annotations.AfterTest; @@ -32,39 +35,106 @@ import org.testng.annotations.Test; import java.io.IOException; -import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static io.ballerina.openapi.generators.common.TestUtils.getDiagnostics; +import static io.ballerina.openapi.generators.common.TestUtils.normalizeOpenAPI; /** * All the tests related to the check diagnostic issue in code generators - * {@link BallerinaClientGenerator} util. + * {{@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} util. */ public class BallerinaDiagnosticTests { private static final Path RESDIR = - Paths.get("src/test/resources/generators/client/diagnostic_files").toAbsolutePath(); + Paths.get("src/test/resources/generators/diagnostic_files").toAbsolutePath(); SyntaxTree syntaxTree; List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); Filter filter = new Filter(list1, list2); - @Test(description = "Test openAPI definition to ballerina client source code generation with diagnostic issue", + @Test(description = "Test openAPI definition to ballerina client source code generation with remote functions", dataProvider = "singleFileProviderForDiagnosticCheck") - public void checkDiagnosticIssues(String yamlFile) throws IOException, BallerinaOpenApiException, - FormatterException, URISyntaxException { - CodeGenerator codeGenerator = new CodeGenerator(); + public void checkDiagnosticIssuesWithRemoteFunctions(String yamlFile) throws IOException, BallerinaOpenApiException, + FormatterException { Path definitionPath = RESDIR.resolve(yamlFile); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = normalizeOpenAPI(definitionPath, true, SpecVersion.V30); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false) + .build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); - Assert.assertTrue(diagnostics.isEmpty()); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); } + @Test(description = "Test openAPI definition to ballerina client source code generation with resource functions", + dataProvider = "singleFileProviderForDiagnosticCheck") + public void checkDiagnosticIssuesWithResourceFunctions(String yamlFile) throws IOException, + BallerinaOpenApiException, FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = normalizeOpenAPI(definitionPath, true, SpecVersion.V30); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true) + .build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } + + @Test(description = "Test OpenAPI 3.1 definition to ballerina client source code generation with remote functions", + dataProvider = "fileProviderForOpenAPI31DiagnosticCheck") + public void checkDiagnosticIssuesWithRemoteFunctionsOpenAPIV31(String yamlFile) throws IOException, + BallerinaOpenApiException, FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = normalizeOpenAPI(definitionPath, true, SpecVersion.V31); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false) + .build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } + + @Test(description = "Test OpenAPI 3.1 definition to ballerina client source code generation " + + "with resource functions", + dataProvider = "fileProviderForOpenAPI31DiagnosticCheck") + public void checkDiagnosticIssuesWithResourceFunctionsOpenAPIV31(String yamlFile) throws IOException, + BallerinaOpenApiException, FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = normalizeOpenAPI(definitionPath, true, SpecVersion.V31); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true) + .build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } @DataProvider(name = "singleFileProviderForDiagnosticCheck") public Object[][] singleFileProviderForDiagnosticCheck() { @@ -79,10 +149,63 @@ public Object[][] singleFileProviderForDiagnosticCheck() { {"xml_payload.yaml"}, {"xml_payload_with_ref.yaml"}, {"duplicated_response.yaml"}, - {"complex_oneOf_schema.yaml"} + {"complex_oneOf_schema.yaml"}, + {"request_body_ref.yaml"}, + {"vendor_specific_mime_types.yaml"}, + {"requestBody_reference_has_inline_object_content_type.yaml"}, + {"ballerinax_connector_tests/ably.yaml"}, + {"ballerinax_connector_tests/azure.iot.yaml"}, + //TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1440 +// {"ballerinax_connector_tests/beezup.yaml"}, + {"ballerinax_connector_tests/files.com.yaml"}, + {"ballerinax_connector_tests/openweathermap.yaml"}, + {"ballerinax_connector_tests/soundcloud.yaml"}, + {"ballerinax_connector_tests/stripe.yaml"}, + {"ballerinax_connector_tests/vimeo.yaml"}, + {"ballerinax_connector_tests/ynab.yaml"}, + {"ballerinax_connector_tests/zoom.yaml"}, }; } + @DataProvider(name = "fileProviderForOpenAPI31DiagnosticCheck") + public Object[][] fileProviderForOprnAPI31DiagnosticCheck() { + return new Object[][] { + {"petstore_server_with_base_path.yaml"}, + {"petstore_get.yaml"}, + {"openapi_display_annotation.yaml"}, + {"header_parameter.yaml"}, + {"petstore_post.yaml"}, + {"petstore_with_oneOf_response.yaml"}, + {"response_nested_array.yaml"}, + {"xml_payload.yaml"}, + {"xml_payload_with_ref.yaml"}, + {"duplicated_response.yaml"}, + {"complex_oneOf_schema.yaml"}, + {"request_body_ref.yaml"}, + {"vendor_specific_mime_types.yaml"}, + {"ballerinax_connector_tests/ably.yaml"}, + {"ballerinax_connector_tests/azure.iot.yaml"}, + //TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1440 +// {"ballerinax_connector_tests/beezup.yaml"}, + {"ballerinax_connector_tests/files.com.yaml"}, + {"ballerinax_connector_tests/openweathermap.yaml"}, + {"ballerinax_connector_tests/soundcloud.yaml"}, +// {"ballerinax_connector_tests/stripe.yaml"}, // not working due to anyOf schema in parameters + {"ballerinax_connector_tests/vimeo.yaml"}, + {"ballerinax_connector_tests/ynab.yaml"}, + {"ballerinax_connector_tests/zoom.yaml"}, + {"3.1.0_openapis/adyen_accountservice.yaml"}, +// {"3.1.0_openapis/codat_accounting.yaml"}, // openapi file has errors +// {"3.1.0_openapis/codat_bank_feeds.yaml"}, // openapi file has errors +// {"3.1.0_openapis/disclosure.yaml"}, // openapi file has errors + {"3.1.0_openapis/listennotes.yaml"}, + {"3.1.0_openapis/placekit.yaml"}, + {"3.1.0_openapis/urlbox.yaml"}, +// {"3.1.0_openapis/vercel.yaml"}, // uncomment when /openapi-tools/issues/1332 is fixed + {"3.1.0_openapis/webscraping.yaml"}, + {"3.1.0_openapis/wolframalpha.yaml"} + }; + } @AfterTest public void cleanUp() throws IOException { TestUtils.deleteGeneratedFiles(); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ComparedGeneratedFileTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ComparedGeneratedFileTests.java index 059071862..877374549 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ComparedGeneratedFileTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ComparedGeneratedFileTests.java @@ -19,11 +19,14 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.openapi.generators.common.TestUtils; import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.FormatterException; import org.testng.Assert; @@ -42,7 +45,7 @@ import static io.ballerina.openapi.generators.common.TestUtils.getDiagnostics; /** - * All the tests related to the {@link BallerinaClientGenerator} util. + * All the tests related to the {{@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} util. */ public class ComparedGeneratedFileTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); @@ -61,9 +64,13 @@ public void generateClientForJira() throws IOException, BallerinaOpenApiExceptio // Path definitionPath = RES_DIR.resolve("swagger/request_body_oneOf_scenarios.yaml"); Path definitionPath = RES_DIR.resolve("openapi.yaml"); Path expectedPath = RES_DIR.resolve("file_provider/ballerina/jira_openapi.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); Assert.assertTrue(diagnostics.isEmpty()); @@ -76,12 +83,18 @@ public void openApiToBallerinaCodeGenTestForClient(String yamlFile, String expe BallerinaOpenApiException, FormatterException, URISyntaxException { Path definitionPath = RES_DIR.resolve("file_provider/swagger/" + yamlFile); Path expectedPath = RES_DIR.resolve("file_provider/ballerina/" + expectedFile); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); - Assert.assertTrue(diagnostics.isEmpty()); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -95,7 +108,13 @@ public Object[][] fileProviderForFilesComparison() { {"api2pdf.yaml", "api2pdf.bal"}, {"nillable_response.yaml", "nillable_response.bal"}, {"nillable_union_response.yaml", "nillable_union_response.bal"}, - {"duplicated_response.yaml", "duplicated_response.bal"} + {"duplicated_response.yaml", "duplicated_response.bal"}, + {"multiline_param_comment.yaml", "multiline_param_comment.bal"}, + {"description_with_special_characters.yaml", "description_with_special_characters.bal"}, + {"header_with_enum.yaml", "header_with_enum.bal"}, + {"incorrect_format.yaml", "incorrect_format.bal"}, + {"format_types_v3_0.yaml", "format_types_v3_0.bal"}, + {"format_types_v3_1.yaml", "format_types_v3_1.bal"} }; } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/EnumGenerationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/EnumGenerationTests.java new file mode 100644 index 000000000..c4213171d --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/EnumGenerationTests.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. + * + * 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.openapi.generators.client; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.openapi.generators.common.TestUtils; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.swagger.v3.oas.models.OpenAPI; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +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.openapi.generators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; +import static io.ballerina.openapi.generators.common.TestUtils.getDiagnostics; +import static io.ballerina.openapi.generators.common.TestUtils.getOpenAPI; + +/** + * Test cases for generating ballerina parameters for openapi parameters with enum schemas. + */ +public class EnumGenerationTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); + + List list1 = new ArrayList<>(); + List list2 = new ArrayList<>(); + Filter filter = new Filter(list1, list2); + @Test(description = "Tests for all the enum scenarios in remote function parameter generation:" + + "Use case 01 : Enum in query parameter" + + "Use case 02 : Enums in path parameter" + + "Use case 03 : Enum in header parameter" + + "Use case 04 : Enum in reusable parameter" + + "Use case 05 : Enum in parameter with referenced schema") + public void generateRemoteParametersWithEnums() throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_enum.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/parameters_with_enum.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + Assert.assertTrue(diagnostics.isEmpty()); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Tests for all the nullable enum scenarios in remote function parameter generation:" + + "Use case 01 : Nullable enum in query parameter" + + "Use case 02 : Nullable enum in path parameter" + + "Use case 03 : Nullable enum in header parameter" + + "Use case 04 : Nullable enum in reusable parameter" + + "Use case 05 : Nullable enum in parameter with referenced schema") + public void generateRemoteParametersWithNullableEnums() throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_nullable_enums.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/parameters_with_nullable_enums.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + Assert.assertTrue(diagnostics.isEmpty()); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Tests for all the enum scenarios in resource function parameter generation:" + + "Use case 01 : Enum in query parameter" + + "Use case 02 : Enums in path parameter" + + "Use case 03 : Enum in header parameter" + + "Use case 04 : Enum in reusable parameter" + + "Use case 05 : Enum in parameter with referenced schema") + public void generateResourceParametersWithEnums() throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_enum.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/paramters_with_enum_resource.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + Assert.assertTrue(diagnostics.isEmpty()); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Tests for all the nullable enum scenarios in resource function parameter generation:" + + "Use case 01 : Nullable enum in query parameter" + + "Use case 02 : Nullable enum in path parameter" + + "Use case 03 : Nullable enum in header parameter" + + "Use case 04 : Nullable enum in reusable parameter" + + "Use case 05 : Nullable enum in parameter with referenced schema") + public void generateResourceParametersWithNullableEnums() throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_nullable_enums.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/parameters_with_nullable_enums_resource.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + List diagnostics = getDiagnostics(syntaxTree, openAPI, ballerinaClientGenerator); + Assert.assertTrue(diagnostics.isEmpty()); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test unsupported nullable path parameter with enums", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Path parameter value cannot be null.") + public void testNullablePathParamWithEnum() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPI(RES_DIR.resolve("swagger/path_param_nullable_enum.yaml")); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + SyntaxTree syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + } + + @AfterMethod + private void deleteGeneratedFiles() { + try { + TestUtils.deleteGeneratedFiles(); + } catch (IOException ignored) { + } + } + + @AfterClass + public void cleanUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FilterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FilterTests.java index a4e727d9a..9371694d2 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FilterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FilterTests.java @@ -19,11 +19,12 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; -import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; import java.io.IOException; @@ -52,24 +53,32 @@ public void testWithTag() throws IOException, BallerinaOpenApiException { list2.clear(); list1.add("Data for all countries"); Filter filter = new Filter(list1, list2); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "With Operation filter") - public void testWithOperation() throws IOException, BallerinaOpenApiException, FormatterException { + public void testWithOperation() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("file_provider/swagger/operation.yaml"); Path expectedPath = RES_DIR.resolve("file_provider/ballerina/operation.bal"); list1.clear(); list2.clear(); list2.add("getCountryList"); Filter filter = new Filter(list1, list2); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionBodyNodeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionBodyNodeTests.java index 5927304e8..9351a682c 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionBodyNodeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionBodyNodeTests.java @@ -19,8 +19,11 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.FunctionBodyNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.openapi.core.generators.client.BallerinaUtilGenerator; +import io.ballerina.openapi.core.generators.client.FunctionBodyGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.PathItem; @@ -41,11 +44,11 @@ import static io.ballerina.openapi.generators.common.TestUtils.getOpenAPI; /** - * All the tests related to the FunctionBodyNode generation in {@link BallerinaClientGenerator} - * util. + * All the tests related to the FunctionBodyNode generation in { + * {@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} util. */ public class FunctionBodyNodeTests { - private static final Path RESDIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); + private static final Path RESDIR = Paths.get("src/test/resources/generators").toAbsolutePath(); private static final Path clientPath = RESDIR.resolve("ballerina_project/client.bal"); private static final Path schemaPath = RESDIR.resolve("ballerina_project/types.bal"); @@ -100,32 +103,31 @@ public Object[][] dataProviderForFunctionBody() { "return response;}"}, {"diagnostic_files/xml_payload_with_ref.yaml", "/pets", "{string resourcePath = string `/pets`;" + "http:Request request = new;" + - "json jsonBody = check payload.cloneWithType(json);" + + "json jsonBody = payload.toJson();" + "xml? xmlBody = check xmldata:fromJson(jsonBody);" + "request.setPayload(xmlBody, \"application/xml\");" + "http:Response response = check self.clientEp->post(resourcePath, request);" + "return response;}"}, - {"swagger/response_type_order.yaml", "/pet/{petId}", + {"client/swagger/response_type_order.yaml", "/pet/{petId}", "{string resourcePath = string `/pet/${getEncodedUri(petId)}`;" + "Pet response = check self.clientEp->get(resourcePath);" + "return response;}"}, - {"swagger/text_request_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + + {"client/swagger/text_request_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + "http:Request request = new;" + - "json jsonBody = check payload.cloneWithType(json);" + + "json jsonBody = payload.toJson();" + "request.setPayload(jsonBody, \"text/json\");" + "json response = check self.clientEp->post(resourcePath, request);" + "return response;}"}, - {"swagger/pdf_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + - "http:Request request = new;" + - "request.setPayload(payload, \"application/pdf\");" + + {"client/swagger/pdf_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + + "// TODO: Update the request as needed;\n" + "http:Response response = check self.clientEp->post(resourcePath, request);" + "return response;}"}, - {"swagger/image_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + + {"client/swagger/image_payload.yaml", "/pets", "{string resourcePath = string `/pets`;" + "http:Request request = new;" + "request.setPayload(payload, \"image/png\");" + "http:Response response = check self.clientEp->post(resourcePath, request);" + "return response;}"}, - {"swagger/multipart_formdata_custom.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + {"client/swagger/multipart_formdata_custom.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + "http:Request request = new;\n" + "map encodingMap = {\"profileImage\": {contentType: \"image/png\", headers: " + "{\"X-Custom-Header\": xCustomHeader}}, \"id\":{headers: {\"X-Custom-Header\": " + @@ -134,7 +136,28 @@ public Object[][] dataProviderForFunctionBody() { "mime:Entity[] bodyParts = check createBodyParts(payload, encodingMap);\n" + "request.setBodyParts(bodyParts);\n" + "http:Response response = check self.clientEp->post(resourcePath, request);\n" + - "return response;}"} + "return response;}"}, + {"client/swagger/empty_object_responnse.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + " // TODO: Update the request as needed;\n" + + " json response = check self.clientEp->post(resourcePath, request);\n" + + " return response;}"}, + {"client/swagger/map_schema_response.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + " // TODO: Update the request as needed;\n" + + " json response = check self.clientEp->post(resourcePath, request);\n" + + " return response;}"}, + {"client/swagger/array_response_pdf.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + " // TODO: Update the request as needed;\n" + + " http:Response response = check self.clientEp->post(resourcePath, request);\n" + + " return response;}"}, + {"client/swagger/any_type_response.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + " // TODO: Update the request as needed;\n" + + " http:Response response = check self.clientEp->post(resourcePath, request);\n" + + " return response;}"}, + {"client/swagger/return_type/no_response.yaml", "/pets", "{string resourcePath = string `/pets`;\n" + + " map queryParam = {\"limit\": 'limit};\n" + + " resourcePath = resourcePath + check getPathForQueryParam(queryParam);\n" + + " http:Response response = check self.clientEp->get(resourcePath);\n" + + " return response;}"} }; } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureNodeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureNodeTests.java index bb5854470..2efd0074e 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureNodeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureNodeTests.java @@ -25,10 +25,11 @@ import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.SeparatedNodeList; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.FunctionSignatureGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.AfterTest; @@ -44,7 +45,8 @@ import static io.ballerina.openapi.generators.common.TestUtils.getOpenAPI; /** - * All the tests related to the functionSignatureNode in {@link BallerinaClientGenerator} util. + * All the tests related to the functionSignatureNode in { + * {@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator} util. */ public class FunctionSignatureNodeTests { private static final Path RESDIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); @@ -79,7 +81,7 @@ public void getFunctionSignatureNodeTests() throws IOException, BallerinaOpenApi Assert.assertEquals(param03.typeName().toString(), "string"); Assert.assertEquals(param04.paramName().orElseThrow().text(), "pages"); - Assert.assertEquals(param04.typeName().toString(), "int[]"); + Assert.assertEquals(param04.typeName().toString(), "decimal[]"); ReturnTypeDescriptorNode returnTypeNode = signature.returnTypeDesc().orElseThrow(); Assert.assertEquals(returnTypeNode.type().toString(), "Product[]|error"); @@ -123,8 +125,7 @@ public void testFunctionSignatureNodeForJSONPayload() throws IOException, Baller @Test(description = "Test for generate function signature for multipart custom header") public void testFunctionSignatureNodeForMultipartCustomHeader() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RESDIR.resolve("swagger/multipart_formdata_custom.yaml"), true); FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(openAPI, new BallerinaTypesGenerator(openAPI), new ArrayList<>(), false); @@ -135,7 +136,7 @@ public void testFunctionSignatureNodeForMultipartCustomHeader() throws IOExcepti RequiredParameterNode param01 = (RequiredParameterNode) parameters.get(0); Assert.assertEquals(param01.paramName().orElseThrow().text(), "payload"); - Assert.assertEquals(param01.typeName().toString(), "PetsBody"); + Assert.assertEquals(param01.typeName().toString(), "Pets_body"); RequiredParameterNode param02 = (RequiredParameterNode) parameters.get(1); Assert.assertEquals(param02.paramName().orElseThrow().text(), "xAddressHeader"); @@ -171,6 +172,34 @@ public void getFunctionSignatureForStringArrayResponse() throws IOException, Bal Assert.assertEquals(returnTypeNode.type().toString(), "string[]|error"); } + @Test(description = "Test parameter generation for request body with reference") + public void getFunctionSignatureForRequestBodyWithRef() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPI(RESDIR.resolve("swagger/request_body_with_ref.yaml")); + FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(openAPI, + new BallerinaTypesGenerator(openAPI), new ArrayList<>(), false); + FunctionSignatureNode signature = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/pets").getPost(), new ArrayList<>()); + SeparatedNodeList parameters = signature.parameters(); + Assert.assertFalse(parameters.isEmpty()); + RequiredParameterNode param01 = (RequiredParameterNode) parameters.get(0); + Assert.assertEquals(param01.paramName().orElseThrow().text(), "payload"); + Assert.assertEquals(param01.typeName().toString(), "CreatedPet_RequestBody"); + } + + @Test(description = "Test parameter generation for request body with unsupported (application/pdf) media type") + public void getFunctionSignatureForUnsupportedRequests() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPI(RESDIR.resolve("swagger/pdf_payload.yaml")); + FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(openAPI, + new BallerinaTypesGenerator(openAPI), new ArrayList<>(), false); + FunctionSignatureNode signature = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/pets").getPost(), new ArrayList<>()); + SeparatedNodeList parameters = signature.parameters(); + Assert.assertFalse(parameters.isEmpty()); + RequiredParameterNode param01 = (RequiredParameterNode) parameters.get(0); + Assert.assertEquals(param01.paramName().orElseThrow().text(), "request"); + Assert.assertEquals(param01.typeName().toString(), "http:Request"); + } + @Test(description = "Test unsupported nested array type query parameter generation", expectedExceptions = BallerinaOpenApiException.class, expectedExceptionsMessageRegExp = "Unsupported parameter type is found in the parameter : .*") @@ -193,6 +222,30 @@ public void testArrayQueryParamWithNoTypeGeneration() throws IOException, Baller .get("/dogs").getGet(), new ArrayList<>()); } + @Test(description = "Test for generate function signature for an integer request") + public void testNumericFunctionSignatureJSONPayload() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPI(RESDIR.resolve("swagger/integer_request_payload.yaml")); + FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(openAPI, + new BallerinaTypesGenerator(openAPI), new ArrayList<>(), false); + FunctionSignatureNode petSignature = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/pets").getPost(), new ArrayList<>()); + FunctionSignatureNode ownerSignature = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/owners").getPost(), new ArrayList<>()); + SeparatedNodeList parameters = petSignature.parameters(); + Assert.assertFalse(parameters.isEmpty()); + RequiredParameterNode petParams = (RequiredParameterNode) parameters.get(0); + RequiredParameterNode ownerParams = (RequiredParameterNode) ownerSignature.parameters().get(0); + + Assert.assertEquals(petParams.paramName().orElseThrow().text(), "payload"); + Assert.assertEquals(petParams.typeName().toString(), "int:Signed32"); + Assert.assertEquals(ownerParams.typeName().toString(), "int"); + + ReturnTypeDescriptorNode petReturnTypeNode = petSignature.returnTypeDesc().orElseThrow(); + Assert.assertEquals(petReturnTypeNode.type().toString(), "int:Signed32|error"); + ReturnTypeDescriptorNode ownerReturnTypeNode = ownerSignature.returnTypeDesc().orElseThrow(); + Assert.assertEquals(ownerReturnTypeNode.type().toString(), "int|error"); + } + @AfterTest private void deleteGeneratedFiles() { try { diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureReturnTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureReturnTypeTests.java index 2e0ca0359..564405ed8 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureReturnTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/FunctionSignatureReturnTypeTests.java @@ -18,8 +18,9 @@ package io.ballerina.openapi.generators.client; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.FunctionReturnTypeGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.Test; @@ -33,7 +34,7 @@ /** * All the tests related to the functionSignatureNode Return type tests in - * {@link BallerinaClientGenerator} util. + * {{@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} util. */ public class FunctionSignatureReturnTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); @@ -73,7 +74,7 @@ public void getReturnTypeForMapSchema() throws IOException, BallerinaOpenApiExce new BallerinaTypesGenerator(array), new ArrayList<>()); String returnType = functionReturnType.getReturnType(array.getPaths().get("/products").getGet(), true); - Assert.assertEquals(returnType, "TestsProductsResponse|error"); + Assert.assertEquals(returnType, "Inline_response_200|error"); } @Test(description = "Tests for the object response without property and without additional properties") @@ -95,7 +96,7 @@ public void getReturnTypeForMapSchemaWithOutAdditionalProperties() throws IOExce new BallerinaTypesGenerator(array), new ArrayList<>()); String returnType = functionReturnType.getReturnType(array.getPaths().get("/products").getGet(), true); - Assert.assertEquals(returnType, "TestsProductsResponse|error"); + Assert.assertEquals(returnType, "Inline_response_200|error"); } @Test(description = "Tests for the response with no schema") @@ -107,4 +108,25 @@ public void getReturnTypeForResponseWithoutSchema() throws IOException, Ballerin true); Assert.assertEquals(returnType, "json|error"); } + + @Test(description = "Tests for the empty response") + public void getReturnTypeForEmptyResponse() throws IOException, BallerinaOpenApiException { + OpenAPI array = getOpenAPI(RES_DIR.resolve("swagger/return_type/no_response.yaml")); + FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(array, + new BallerinaTypesGenerator(array), new ArrayList<>()); + String returnType = functionReturnType.getReturnType(array.getPaths().get("/pets").getGet(), + true); + Assert.assertEquals(returnType, "http:Response|error"); + } + + @Test(description = "Tests for the response with additional properties in OpenAPI 3.1 spec") + public void getReturnTypeForAdditionalPropertySchema() throws IOException, BallerinaOpenApiException { + OpenAPI array = getOpenAPI(RES_DIR.resolve("swagger/return_type/" + + "response_with_only_additional_schema.yaml")); + FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(array, + new BallerinaTypesGenerator(array), new ArrayList<>()); + String returnType = functionReturnType.getReturnType(array.getPaths().get("/store/inventory").getGet(), + true); + Assert.assertEquals(returnType, "json|error"); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/HeadersTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/HeadersTests.java index b179b09b7..ad6bab9e2 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/HeadersTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/HeadersTests.java @@ -18,9 +18,11 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -44,55 +46,89 @@ public class HeadersTests { @Test(description = "Test for header that comes under the parameter section") public void getHeaderTests() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/header_parameter.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/header_parameter.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for header that comes under the parameter section") public void getHeaderTestsWithoutParameter() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/header_without_parameter.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/header_without_parameter.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for header with default values") public void getHeaderTestsWithDefaultValues() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/header_param_with_default_value.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/header_param_with_default_value.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for optional headers without default values") public void getOptionalHeaderTestsWithoutDefaultValues() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/header_optional.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/header_optional.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for headers with delete values") public void getHeaderWithDeleteOperation() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/delete_with_header.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/delete_with_header.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, - false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Tests for integer type headers") + public void testIntegerTypeHeaders() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/header_integer_signed32.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/header_integer_signed32.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ImportsTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ImportsTests.java index a83bc498d..3b97544f7 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ImportsTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ImportsTests.java @@ -19,7 +19,7 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; -import io.ballerina.openapi.cmd.Filter; +import io.ballerina.openapi.core.model.Filter; import org.testng.Assert; import org.testng.annotations.Test; @@ -28,7 +28,7 @@ import java.util.ArrayList; import java.util.List; -import static io.ballerina.openapi.generators.GeneratorUtils.getImportDeclarationNode; +import static io.ballerina.openapi.core.GeneratorUtils.getImportDeclarationNode; /** * This tests class for the tests imports in the generation. diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/NoServerURLTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/NoServerURLTest.java index 97656d38a..b7e2e5542 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/NoServerURLTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/NoServerURLTest.java @@ -2,9 +2,13 @@ import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.cmd.BallerinaCodeGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaAuthConfigGenerator; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.openapi.generators.common.TestConstants; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; @@ -30,12 +34,17 @@ public class NoServerURLTest { @Test(description = "Test for no server url with no security schema given") public void getClientForNoServerURL() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); + BallerinaCodeGenerator codeGenerator = new BallerinaCodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/missing_server_url.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/missing_server_url.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/OneOfResponsesTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/OneOfResponsesTests.java index f138b0ab3..b861db2e3 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/OneOfResponsesTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/OneOfResponsesTests.java @@ -18,8 +18,9 @@ package io.ballerina.openapi.generators.client; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.FunctionReturnTypeGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.Test; @@ -33,7 +34,7 @@ /** * All the tests related to the functionSignatureNode Return type tests as oneOf typein - * {@link BallerinaClientGenerator} util. + * {{@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator}} util. */ public class OneOfResponsesTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/client").toAbsolutePath(); @@ -45,7 +46,7 @@ public void getReturnTypeOneOfArray() throws IOException, BallerinaOpenApiExcept FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(response, ballerinaSchemaGenerator, new ArrayList<>()); Assert.assertEquals(functionReturnType.getReturnType(response.getPaths().get("/pet").getGet(), - true), "ChannelDetails[]|string[]|error"); + true), "Inline_response_2XX|error"); } @Test(description = "Tests for returnType when response has array oneOf when it has function body") @@ -55,6 +56,6 @@ public void getReturnTypeOneOfArrayInTargetType() throws IOException, BallerinaO FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator(response, ballerinaSchemaGenerator, new ArrayList<>()); Assert.assertEquals(functionReturnType.getReturnType(response.getPaths().get("/pet").getGet(), - false), "OneOfOperationId01Response|error"); + false), "Inline_response_2XX|error"); } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/PathParameterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/PathParameterTests.java index 0eec2d5b7..0f3eb02fc 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/PathParameterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/PathParameterTests.java @@ -18,9 +18,13 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.cmd.BallerinaCodeGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -49,44 +53,61 @@ public void generatePathWithPathParameterTests() throws IOException, BallerinaOp // "/v1/{version}/v2/{limit}", "/v1/${'version}/v2/${'limit}" // "/v1/{age}/v2/{name}", "/v1/${age}/v2/${name}" - CodeGenerator codeGenerator = new CodeGenerator(); + BallerinaCodeGenerator codeGenerator = new BallerinaCodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/path_parameter_valid.yaml"); Path expectedPath = RESDIR.resolve("ballerina/path_parameter_valid.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for path parameter with referenced schema") public void generatePathParamWithReferencedSchema() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/path_param_with_ref_schemas.yaml"); Path expectedPath = RESDIR.resolve("ballerina/path_param_with_ref_schema.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client while handling special characters in path parameter name") public void generateFormattedPathParamName() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/path_parameter_special_name.yaml"); Path expectedPath = RESDIR.resolve("ballerina/path_parameter_with_special_name.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client with duplicated path parameter name in the path") public void generateFormattedDuplicatedPathParamName() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/path_param_duplicated_name.yaml"); Path expectedPath = RESDIR.resolve("ballerina/path_param_duplicated_name.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -96,9 +117,13 @@ public void generateFormattedDuplicatedPathParamName() throws IOException, Balle expectedExceptionsMessageRegExp = "Invalid path parameter data type for the parameter: .*") public void testInvalidPathParameterType() throws IOException, BallerinaOpenApiException { Path definitionPath = RESDIR.resolve("swagger/path_parameter_invalid.yaml"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); ballerinaClientGenerator.generateSyntaxTree(); } @@ -107,9 +132,63 @@ public void testInvalidPathParameterType() throws IOException, BallerinaOpenApiE expectedExceptionsMessageRegExp = "Unsupported OAS data type .*") public void testInvalidDataType() throws IOException, BallerinaOpenApiException { Path definitionPath = RESDIR.resolve("swagger/path_parameter_invalid02.yaml"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); ballerinaClientGenerator.generateSyntaxTree(); } + + @Test (description = "Generate Client for path parameter with anyOf, oneOf type") + public void unionPathParameter() throws IOException, BallerinaOpenApiException { + Path definitionPath = RESDIR.resolve("swagger/union_path_parameter.yaml"); + Path expectedPath = RESDIR.resolve("ballerina/union_path_parameter.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + + Path expectedTypePath = RESDIR.resolve("ballerina/union_path_types.bal"); + BallerinaTypesGenerator ballerinaTypesGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree typeSyntaxTree = ballerinaTypesGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedTypePath, typeSyntaxTree); + } + + @Test(description = "When path parameter has given allOf data type in ballerina", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Ballerina does not support object type path .*") + public void allOfPathParameter() throws IOException, BallerinaOpenApiException { + Path definitionPath = RESDIR.resolve("swagger/allOf_path_parameter.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + ballerinaClientGenerator.generateSyntaxTree(); + } + + @Test (description = "Generate Client for path parameter with integer int32 and int64 types") + public void testIntegerPathParameters() throws IOException, BallerinaOpenApiException { + Path definitionPath = RESDIR.resolve("swagger/integer_signed32_path_parameter.yaml"); + Path expectedPath = RESDIR.resolve("ballerina/integer_signed32_path_parameter.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/QueryParameterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/QueryParameterTests.java index b3a00f0f7..5ecf1d2ef 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/QueryParameterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/QueryParameterTests.java @@ -18,11 +18,12 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; -import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; import java.io.IOException; @@ -44,61 +45,97 @@ public class QueryParameterTests { SyntaxTree syntaxTree; @Test(description = "Generate Client for query parameter has default value") - public void generateQueryParamWithDefault() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); + public void generateQueryParamWithDefault() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query_param_with_default_value.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/query_param_with_default_value.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for query parameter without default value") public void generateQueryParamWithOutDefault() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/query_param_without_default_value.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/query_param_without_default_value.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for query parameter with referenced schema") public void generateQueryParamWithReferencedSchema() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/query_param_with_ref_schema.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/query_param_with_ref_schema.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate query parameters when both apikeys and http/OAuth is supported") public void genQueryParamsForCombinationOfApiKeyAndHTTPOrOAuth() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/combination_of_apikey_and_http_oauth.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/combination_of_apikey_and_http_oauth.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate encoding map for query parameters") public void genQueryParamEncodingMap() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/queryparam_encoding_map_gen.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/queryparam_encoding_map_gen.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Generate Client for query parameter has integer values") + public void testValidIntegerQueryParam() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/query_param_with_integer_value.yaml"); + Path expectedPath = RES_DIR.resolve("ballerina/query_param_with_integer_value.bal"); + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RemoteFunctionNameValidationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RemoteFunctionNameValidationTests.java index e3f5639cd..12604f9df 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RemoteFunctionNameValidationTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RemoteFunctionNameValidationTests.java @@ -1,9 +1,11 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -15,7 +17,7 @@ import java.util.ArrayList; import java.util.List; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; /** * check whether the remote function names generated are matching with ballerina standard. @@ -31,13 +33,16 @@ public class RemoteFunctionNameValidationTests { @Test(description = "When path parameter has given unmatch data type in ballerina", expectedExceptions = BallerinaOpenApiException.class, expectedExceptionsMessageRegExp = "OpenAPI definition has errors: " + - "\\R\\ROperationId is missing in the resource path: .*") + "\\ROperationId is missing in the resource path: .*") public void testMissionOperationId() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("petstore_without_operation_id.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, - false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); ballerinaClientGenerator.generateSyntaxTree(); } @@ -52,7 +57,7 @@ public void testFunctionNameGeneration(String operationId, String expectedFuncti public Object[][] dataProvider() { return new Object[][]{ {"get-pet-name", "getPetName"}, - {"GET_Add_permission", "getAddPermission"}, + {"GET_Add_permission", "gET_Add_permission"}, {"ListBankAccount", "listBankAccount"}, {"chat.media.download", "chatMediaDownload"} }; diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RequestBodyTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RequestBodyTests.java index 52e1afb4d..5556defcb 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RequestBodyTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/RequestBodyTests.java @@ -19,9 +19,11 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; @@ -36,7 +38,8 @@ import static io.ballerina.openapi.generators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; /** - * All the tests related to the functionSignatureNode in {@link BallerinaClientGenerator} util when have diffrent + * All the tests related to the functionSignatureNode in + * {@link io.ballerina.openapi.core.generators.client.BallerinaClientGenerator} util when have diffrent * scenarios in Request Body. */ public class RequestBodyTests { @@ -51,10 +54,14 @@ public class RequestBodyTests { @Test(description = "Test for generate request body payload when operation has request body") public void testForRequestBody() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_basic_scenarios.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_basic_scenarios.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -62,10 +69,14 @@ public void testForRequestBody() throws IOException, BallerinaOpenApiException { @Test(description = "Test for generate request body payload when operation has request body with AllOf scenarios") public void testForRequestBodyWithAllOf() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_allOf_scenarios.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_allOf_scenarios.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -73,10 +84,14 @@ public void testForRequestBodyWithAllOf() throws IOException, BallerinaOpenApiEx @Test(description = "Test for generate request body payload when operation has request body OneOf scenarios") public void testForRequestBodyWithOneOf() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_oneOf_scenarios.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_oneOf_scenarios.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -84,10 +99,14 @@ public void testForRequestBodyWithOneOf() throws IOException, BallerinaOpenApiEx @Test(description = "Test for generate request body payload with array schema") public void testForRequestBodyWithArraySchema() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_array.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_array.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -95,51 +114,68 @@ public void testForRequestBodyWithArraySchema() throws IOException, BallerinaOpe @Test(description = "Test for generate request body payload with empty array schema") public void testForRequestBodyWithEmptyArraySchema() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_empty_array.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_empty_array.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } - @Test(description = "Test client generation for unsupported request body media type", - expectedExceptions = BallerinaOpenApiException.class) + @Test(description = "Test client generation for unsupported request body media type") public void testRequestBodyWithUnsupportedMediaType() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); + Path expectedPath = RES_DIR.resolve("ballerina/unsupported_request_body.bal"); Path definitionPath = RES_DIR.resolve("swagger/unsupported_request_body.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); - ballerinaClientGenerator.generateSyntaxTree(); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test requestBody validation in GET/DELETE/HEAD operations", expectedExceptions = BallerinaOpenApiException.class, expectedExceptionsMessageRegExp = ".*GET operation cannot have a requestBody.*") public void testGetOrDeleteOrHeadContainRequestBody() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RES_DIR.resolve("swagger/request_body_in_get_delete_head.yaml"); - codeGenerator.normalizeOpenAPI(definitionPath, true); + GeneratorUtils.normalizeOpenAPI(definitionPath, true); } @Test(description = "Test for generating request body when operation has form url encoded media type") public void testRequestBodyWithURLEncodedType() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/url_encoded_payload.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("utils/swagger/url_encoded.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for generating request body when operation has binary octet-stream media type") - public void testRequestBodyWithBinaryOctetStreamMediaType() throws IOException, BallerinaOpenApiException { + public void testRequestBodyWithBinaryOctetStreamMediaType() + throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/binary_format_octet_stream_payload.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/binary_format_octet_stream_payload.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -147,21 +183,29 @@ public void testRequestBodyWithBinaryOctetStreamMediaType() throws IOException, @Test(description = "Test for generating request body when operation has byte octet-stream media type") public void testRequestBodyWithByteOctetStreamMediaType() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/byte_format_octet_stream_payload.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/byte_format_octet_stream_payload.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Test for generating request body when operation has */* media type") - public void testRequestBodyWithAllTypeMediaType() throws IOException, BallerinaOpenApiException { + public void testRequestBodyWithWildCardeMediaType() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/any_types_payload.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/any_types_payload.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -169,10 +213,45 @@ public void testRequestBodyWithAllTypeMediaType() throws IOException, BallerinaO @Test(description = "Test for generating request body when operation has vendor specific media type") public void testRequestBodyWithVendorSpecificMimeType() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/vendor_specific_payload.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/vendor_specific_payload.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body when operation has vendor specific media type " + + "which is a subtype of JSON") + public void testRequestBodyWithVendorSpecificMimeTypeWithJSON() throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/vendor_specific_with_subtype.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/vendor_specific_with_subtype.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body when operation has unsupported text/xx media type") + public void testRequestBodyWithUnsupportedTextMediaType() throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/unsupported_text_media_type.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/unsupported_text_media_type.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -180,10 +259,48 @@ public void testRequestBodyWithVendorSpecificMimeType() throws IOException, Ball @Test(description = "Test for generating request body when operation has multipart form-data media type") public void testRequestBodyWithMultipartMediaType() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/multipart_formdata.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("utils/swagger/multipart_formdata.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body when operation has multipart form-data media type " + + "with no schema") + public void testRequestBodyWithMultipartMediaTypeAndNoSchema() + throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/multipart_formdata_empty.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/mutipart_formdata_empty.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body when operation has multipart form-data media type " + + "with invalid schema") + public void testRequestBodyWithMultipartMediaTypeInvalidSchema() + throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/multipart_binary.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/multipart_binary.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @@ -191,10 +308,61 @@ public void testRequestBodyWithMultipartMediaType() throws IOException, Ballerin @Test(description = "Test for generating request body when schema is empty") public void testRequestBodyWithoutSchema() throws IOException, BallerinaOpenApiException { Path expectedPath = RES_DIR.resolve("ballerina/request_body_without_schema.bal"); - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI( + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( RES_DIR.resolve("swagger/request_body_without_schema.yaml"), true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body with reference") + public void testRequestBodyWithReference() throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/request_body_with_ref.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/request_body_with_ref.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body with octet-stream media type") + public void testWithOctetStreamInRequestBody() + throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/octet_stream_request_payload.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/octet_stream_request_payload.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Test for generating request body with object schema content without properties") + public void testWithRBContentHasObjectSchemaWithoutProperties() + throws IOException, BallerinaOpenApiException { + Path expectedPath = RES_DIR.resolve("ballerina/request_body_has_object_content_without_property.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI( + RES_DIR.resolve("swagger/request_body_has_object_content_without_property.yaml"), true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(true).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ResourceFunctionTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ResourceFunctionTests.java index bc222341b..de3b711a9 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ResourceFunctionTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/ResourceFunctionTests.java @@ -16,11 +16,12 @@ package io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; -import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; import java.io.IOException; @@ -42,44 +43,70 @@ public class ResourceFunctionTests { Filter filter = new Filter(list1, list2); @Test(description = "Generate Client for all methods with resource function") public void generateForAllMethods() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/all_methods.yaml"); Path expectedPath = RESDIR.resolve("ballerina/all_methods.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for headers") public void generateForHeaders() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/header.yaml"); Path expectedPath = RESDIR.resolve("ballerina/header.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for pathParameters") - public void generateForPathParameters() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); + public void generateForPathParameters() throws IOException, BallerinaOpenApiException { Path definitionPath = RESDIR.resolve("swagger/pathParameters.yaml"); Path expectedPath = RESDIR.resolve("ballerina/pathParameters.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } @Test(description = "Generate Client for request body") public void generateForRequestBody() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/request_body.yaml"); Path expectedPath = RESDIR.resolve("ballerina/request_body.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Generate Client for reference path parameters") + public void generateReferenceResolvePath() throws IOException, BallerinaOpenApiException { + Path definitionPath = RESDIR.resolve("swagger/reference_path.yaml"); + Path expectedPath = RESDIR.resolve("ballerina/reference_path.bal"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/UtilGenerationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/UtilGenerationTests.java index c4e00ffdc..69043ba0c 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/UtilGenerationTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/client/UtilGenerationTests.java @@ -6,9 +6,11 @@ import io.ballerina.compiler.syntax.tree.NodeList; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.openapi.generators.common.TestUtils; import io.ballerina.tools.diagnostics.Diagnostic; import io.swagger.v3.oas.models.OpenAPI; @@ -49,10 +51,14 @@ public class UtilGenerationTests { @Test(description = "Test default util file generation") public void testDefaultUtilFileGen() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/no_util.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); SyntaxTree utlisSyntaxTree = ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("client/ballerina/default_util.bal", @@ -62,10 +68,14 @@ public void testDefaultUtilFileGen() throws IOException, BallerinaOpenApiExcepti @Test(description = "Validate the util functions generated for OpenAPI definition with query parameters") public void testUtilFileGenForQueryParams() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/query_param.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List invalidFunctionNames = Arrays.asList(CREATE_FORM_URLENCODED_REQUEST_BODY, GET_MAP_FOR_HEADERS); Assert.assertTrue(checkUtil(invalidFunctionNames, @@ -77,10 +87,14 @@ public void testUtilFileGenForQueryParams() throws IOException, BallerinaOpenApi @Test(description = "Validate the util functions generated for OpenAPI definition with headers") public void testUtilFileGenForHeader() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/header.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List invalidFunctionNames = Arrays.asList(CREATE_FORM_URLENCODED_REQUEST_BODY, GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, GET_SERIALIZED_ARRAY, @@ -94,10 +108,14 @@ public void testUtilFileGenForHeader() throws IOException, BallerinaOpenApiExcep @Test(description = "Validate the util functions generated for OpenAPI definition with URL encoded request body") public void testUtilFileGenURLEncodedRequestBody() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/url_encoded.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List invalidFunctionNames = Arrays.asList(GET_PATH_FOR_QUERY_PARAM, GET_MAP_FOR_HEADERS); Assert.assertTrue(checkUtil(invalidFunctionNames, @@ -110,10 +128,14 @@ public void testUtilFileGenURLEncodedRequestBody() throws IOException, Ballerina "request body with encoding styles specified") public void testUtilFileGenURLEncodedRequestWithEncoding() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/url_encoded_with_map.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List invalidFunctionNames = Arrays.asList(GET_PATH_FOR_QUERY_PARAM, GET_MAP_FOR_HEADERS); Assert.assertTrue(checkUtil(invalidFunctionNames, @@ -125,10 +147,14 @@ public void testUtilFileGenURLEncodedRequestWithEncoding() throws IOException, B @Test(description = "Validate the util functions generated for OpenAPI definition when all the scenarios are given") public void testCompleteUtilFileGen() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/complete_util_gen.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(clientSyntaxTree, openAPI, ballerinaClientGenerator); Assert.assertTrue(diagnostics.isEmpty()); @@ -137,10 +163,14 @@ public void testCompleteUtilFileGen() throws IOException, BallerinaOpenApiExcept @Test(description = "Test the utilsbal file generation when only in:query api-key auth given") public void testApiKeyauthUtilGen() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/apikey_with_no_query_param.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(clientSyntaxTree, openAPI, ballerinaClientGenerator); Assert.assertTrue(diagnostics.isEmpty()); @@ -148,10 +178,14 @@ public void testApiKeyauthUtilGen() throws IOException, BallerinaOpenApiExceptio @Test(description = "Validate the util functions generated for OpenAPI definition with multi part request bodies") public void testMultipartBodyParts() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/multipart_formdata.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(clientSyntaxTree, openAPI, ballerinaClientGenerator); Assert.assertTrue(diagnostics.isEmpty()); @@ -160,10 +194,14 @@ public void testMultipartBodyParts() throws IOException, BallerinaOpenApiExcepti @Test(description = "Validate the util functions generated for OpenAPI definition with multi part " + "request custom bodies") public void testMultipartCustomBodyParts() throws IOException, BallerinaOpenApiException, FormatterException { - CodeGenerator codeGenerator = new CodeGenerator(); Path definitionPath = RESDIR.resolve("swagger/multipart_formdata_custom.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree clientSyntaxTree = ballerinaClientGenerator.generateSyntaxTree(); List diagnostics = getDiagnostics(clientSyntaxTree, openAPI, ballerinaClientGenerator); Assert.assertTrue(diagnostics.isEmpty()); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/GeneratorUtilsTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/GeneratorUtilsTests.java index b09d9ed65..799014a7e 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/GeneratorUtilsTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/GeneratorUtilsTests.java @@ -19,10 +19,9 @@ package io.ballerina.openapi.generators.common; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.Test; @@ -31,9 +30,9 @@ import java.nio.file.Path; import java.nio.file.Paths; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorUtils.extractReferenceType; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; import static io.ballerina.openapi.generators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; -import static io.ballerina.openapi.generators.service.ServiceGenerationUtils.extractReferenceType; /** * This util class for testing functionality for {@GeneratorUtils.java}. @@ -84,8 +83,7 @@ public static void testGenerateReadableName() { @Test(description = "Set record name with removing special Characters") public static void testRecordName() throws IOException, BallerinaOpenApiException { - CodeGenerator codeGenerator = new CodeGenerator(); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("schema/swagger/recordName" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("schema/swagger/recordName" + ".yaml"), false); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/SwaggerParserTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/SwaggerParserTests.java index 503e6e8bd..61b5a20a9 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/SwaggerParserTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/SwaggerParserTests.java @@ -19,9 +19,9 @@ package io.ballerina.openapi.generators.common; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; import org.testng.annotations.Test; @@ -50,6 +50,16 @@ public void generateHandleUnsupportedData() throws IOException, BallerinaOpenAp syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); } + @Test(description = "Functionality tests for swagger parser behaviour when the regex is having syntax errors", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "OpenAPI definition has errors: .*") + public void testInvalidRegexPatterns() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/invalid_pattern_string.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + 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)); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java index eafa7f10f..a9b06d694 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java @@ -6,128 +6,158 @@ public class TestConstants { private static String clientConfigRecordDoc = "" + "# Provides a set of configurations for controlling the behaviours when communicating with a remote " + - "HTTP endpoint."; + "HTTP endpoint.\n" + + "@display {label: \"Connection Config\"}\n"; public static String authConfigRecordDoc = "" + "# Provides Auth configurations needed when communicating with a remote HTTP endpoint."; private static String commonClientConfigurationFields = "# The HTTP version understood by the client\n" + - " string httpVersion = \"1.1\";\n" + + " http:HttpVersion httpVersion = http:HTTP_2_0;\n" + " # Configurations related to HTTP/1.x protocol\n" + - " http:ClientHttp1Settings http1Settings = {};\n" + + " ClientHttp1Settings http1Settings?;\n" + " # Configurations related to HTTP/2 protocol\n" + - " http:ClientHttp2Settings http2Settings = {};\n" + + " http:ClientHttp2Settings http2Settings?;\n" + " # The maximum time to wait (in seconds) for a response before closing the connection\n" + " decimal timeout = 60;\n" + " # The choice of setting `forwarded`/`x-forwarded` header\n" + " string forwarded = \"disable\";\n" + - " # Configurations associated with Redirection\n" + - " http:FollowRedirects? followRedirects = ();\n" + " # Configurations associated with request pooling\n" + - " http:PoolConfiguration? poolConfig = ();\n" + + " http:PoolConfiguration poolConfig?;\n" + " # HTTP caching related configurations\n" + - " http:CacheConfig cache = {};\n" + + " http:CacheConfig cache?;\n" + " # Specifies the way of handling compression (`accept-encoding`) header\n" + " http:Compression compression = http:COMPRESSION_AUTO;\n" + " # Configurations associated with the behaviour of the Circuit Breaker\n" + - " http:CircuitBreakerConfig? circuitBreaker = ();\n" + + " http:CircuitBreakerConfig circuitBreaker?;\n" + " # Configurations associated with retrying\n" + - " http:RetryConfig? retryConfig = ();\n" + - " # Configurations associated with cookies\n" + - " http:CookieConfig? cookieConfig = ();\n" + + " http:RetryConfig retryConfig?;\n" + " # Configurations associated with inbound response size limits\n" + - " http:ResponseLimitConfigs responseLimits = {};\n" + + " http:ResponseLimitConfigs responseLimits?;\n" + " # SSL/TLS-related options\n" + - " http:ClientSecureSocket? secureSocket = ();\n" + + " http:ClientSecureSocket secureSocket?;\n" + " # Proxy server related options\n" + - " http:ProxyConfig? proxy = ();\n" + + " http:ProxyConfig proxy?;\n" + + " # Enables the inbound payload validation functionality which provided by the constraint package. " + + "Enabled by default\n" + + " boolean validation = true; " + "|};"; - + + public static final String CLIENT_HTTP1_SETTINGS = "# Provides settings related to HTTP/1.x protocol.\n" + + "public type ClientHttp1Settings record {|\n" + + " # Specifies whether to reuse a connection for multiple requests\n" + + " http:KeepAlive keepAlive = http:KEEPALIVE_AUTO;\n" + + " # The chunking behaviour of the request\n" + + " http:Chunking chunking = http:CHUNKING_AUTO;\n" + + " # Proxy server related options\n" + + " ProxyConfig proxy?;\n" + + "|};"; + + public static final String PROXY_CONFIG = "" + + "# Proxy server configurations to be used with the HTTP client endpoint.\n" + + "public type ProxyConfig record {|\n" + + " # Host name of the proxy server\n" + + " string host = \"\";\n" + + " # Proxy server port\n" + + " int port = 0;\n" + + " # Proxy server username\n" + + " string userName = \"\";\n" + + " # Proxy server password\n" + + " @display {label: \"\", kind: \"password\"}\n" + + " string password = \"\";\n" + + "|};"; + + public static final String HTTP_BASIC_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:CredentialsConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_BEARER_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_MULTI_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig|http:CredentialsConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_CLIENT_CONFIG_PARAM = - "ClientConfig clientConfig, string serviceUrl = \"https:localhost/8080\""; - public static final String HTTP_CLIENT_CONFIG_PARAM_NO_URL = "ClientConfig clientConfig, string serviceUrl"; + "ConnectionConfig config, string serviceUrl = \"https:localhost/8080\""; + public static final String HTTP_CLIENT_CONFIG_PARAM_NO_URL = "ConnectionConfig config, string serviceUrl"; public static final String HTTP_CLIENT_DECLARATION = "" + - "http:Client httpEp = check new (serviceUrl, clientConfig);"; + "http:Client httpEp = check new (serviceUrl, httpClientConfig);"; public static final String OAUTH2_AUTHORIZATION_CODE_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_CUSTOM_AUTHORIZATION_CODE_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig|OAuth2RefreshTokenGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_IMPLICIT_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_PASSWORD_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:OAuth2PasswordGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_CUSTOM_PASSWORD_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " OAuth2PasswordGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_CLIENT_CRED_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " http:OAuth2ClientCredentialsGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_CUSTOM_CLIENT_CRED_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " OAuth2ClientCredentialsGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_MULTI_FLOWS_CONFIG_REC = "" + clientConfigRecordDoc + - "public type ClientConfig record {|\n" + + "public type ConnectionConfig record {|\n" + " # Configurations related to client authentication\n" + " OAuth2PasswordGrantConfig|http:BearerTokenConfig|OAuth2RefreshTokenGrantConfig auth;\n" + commonClientConfigurationFields; public static final String API_KEY_CONFIG_VAR = "final readonly & ApiKeysConfig apiKeyConfig;"; public static final String API_KEY_CONFIG_NILLABLE_VAR = "final readonly & ApiKeysConfig? apiKeyConfig;"; public static final String API_KEY_CONFIG_PARAM = "" + - "ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, " + + "ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, " + "string serviceUrl = \"https:localhost/8080\""; public static final String AUTH_CONFIG_PARAM = "" + - "AuthConfig authConfig, http:ClientConfiguration clientConfig = {}, " + + "ConnectionConfig config, " + "string serviceUrl = \"https:localhost/8080\""; public static final String API_KEY_CONFIG_PARAM_NO_URL = "" + - "ApiKeysConfig apiKeyConfig, string serviceUrl, http:ClientConfiguration clientConfig = {}"; + "ApiKeysConfig apiKeyConfig, string serviceUrl,ConnectionConfig config = {}"; public static final String API_KEYS_CONFIG_RECORD = "# Provides API key configurations needed when communicating " + "with a remote HTTP endpoint.\n" + "public type ApiKeysConfig record {|\n" + " # API key to authorize requests.\n" + + " @display {label: \"\", kind: \"password\"}\n" + " string appid;\n" + " # API key to authorize requests.\n" + + " @display {label: \"\", kind: \"password\"}\n" + " string apiXKey;\n" + "|};"; + public static final String API_KEY_ASSIGNMENT = "self.apiKeyConfig = apiKeyConfig.cloneReadOnly();"; public static final String MULTIPLE_API_KEY_RECORD = "# Provides API key configurations needed when " + "communicating with a remote HTTP endpoint.\n" + "public type ApiKeysConfig record {|\n" + " # API key to authorize GET requests.\n" + + " @display {label: \"\", kind: \"password\"}\n" + " string appid;\n" + " # API key to authorize POST requests.\n" + + " @display {label: \"\", kind: \"password\"}\n" + " string xApiKey;\n" + "|};"; public static final String MULTI_LINE_API_KEY_DESC = "# Provides API key configurations needed when " + @@ -144,6 +174,117 @@ public class TestConstants { " # Learn how to set the Authorization header inside Postman " + "https://learning.postman.com/docs/postman/sending-api-requests/authorization/#api-key\n" + " # Go to Unify to grab your API KEY https://openweathermap/me/api-keys\n" + + " @display {label: \"\", kind: \"password\"}\n" + " string appid;\n" + "|};"; + + public static final String CONNECTION_CONFIG_NO_AUTH = "" + + "# Provides a set of configurations for controlling the behaviours when communicating with a " + + "remote HTTP endpoint.\n" + + "@display {label: \"Connection Config\"}\n" + + "public type ConnectionConfig record {|\n" + + " # The HTTP version understood by the client\n" + + " http:HttpVersion httpVersion = http:HTTP_2_0;\n" + + " # Configurations related to HTTP/1.x protocol\n" + + " ClientHttp1Settings http1Settings?;\n" + + " # Configurations related to HTTP/2 protocol\n" + + " http:ClientHttp2Settings http2Settings?;\n" + + " # The maximum time to wait (in seconds) for a response before closing the connection\n" + + " decimal timeout = 60;\n" + + " # The choice of setting `forwarded`/`x-forwarded` header\n" + + " string forwarded = \"disable\";\n" + + " # Configurations associated with request pooling\n" + + " http:PoolConfiguration poolConfig?;\n" + + " # HTTP caching related configurations\n" + + " http:CacheConfig cache?;\n" + + " # Specifies the way of handling compression (`accept-encoding`) header\n" + + " http:Compression compression = http:COMPRESSION_AUTO;\n" + + " # Configurations associated with the behaviour of the Circuit Breaker\n" + + " http:CircuitBreakerConfig circuitBreaker?;\n" + + " # Configurations associated with retrying\n" + + " http:RetryConfig retryConfig?;\n" + + " # Configurations associated with inbound response size limits\n" + + " http:ResponseLimitConfigs responseLimits?;\n" + + " # SSL/TLS-related options\n" + + " http:ClientSecureSocket secureSocket?;\n" + + " # Proxy server related options\n" + + " http:ProxyConfig proxy?;\n" + + " # Enables the inbound payload validation functionality which provided by the constraint package. " + + "Enabled by default\n" + + " boolean validation = true;\n" + + "|};"; + public static final String CONNECTION_CONFIG_MIXED_AUTH = "" + + "# Provides a set of configurations for controlling the behaviours when communicating with a " + + "remote HTTP endpoint.\n" + + "@display {label: \"Connection Config\"}\n" + + "public type ConnectionConfig record {|\n" + + " # Provides Auth configurations needed when communicating with a remote HTTP endpoint.\n" + + " OAuth2ClientCredentialsGrantConfig|http:BearerTokenConfig|" + + " OAuth2RefreshTokenGrantConfig|ApiKeysConfig auth;\n" + + " # The HTTP version understood by the client\n" + + " http:HttpVersion httpVersion = http:HTTP_2_0;\n" + + " # Configurations related to HTTP/1.x protocol\n" + + " ClientHttp1Settings http1Settings?;\n" + + " # Configurations related to HTTP/2 protocol\n" + + " http:ClientHttp2Settings http2Settings?;\n" + + " # The maximum time to wait (in seconds) for a response before closing the connection\n" + + " decimal timeout = 60;\n" + + " # The choice of setting `forwarded`/`x-forwarded` header\n" + + " string forwarded = \"disable\";\n" + + " # Configurations associated with request pooling\n" + + " http:PoolConfiguration poolConfig?;\n" + + " # HTTP caching related configurations\n" + + " http:CacheConfig cache?;\n" + + " # Specifies the way of handling compression (`accept-encoding`) header\n" + + " http:Compression compression = http:COMPRESSION_AUTO;\n" + + " # Configurations associated with the behaviour of the Circuit Breaker\n" + + " http:CircuitBreakerConfig circuitBreaker?;\n" + + " # Configurations associated with retrying\n" + + " http:RetryConfig retryConfig?;\n" + + " # Configurations associated with inbound response size limits\n" + + " http:ResponseLimitConfigs responseLimits?;\n" + + " # SSL/TLS-related options\n" + + " http:ClientSecureSocket secureSocket?;\n" + + " # Proxy server related options\n" + + " http:ProxyConfig proxy?;\n" + + " # Enables the inbound payload validation functionality which provided by the constraint package. " + + "Enabled by default\n" + + " boolean validation = true;\n" + + "|};"; + + public static final String CONNECTION_CONFIG_HTTP_VERSION_1_1 = "" + + "# Provides a set of configurations for controlling the behaviours when communicating " + + "with a remote HTTP endpoint.\n" + + "@display {label: \"Connection Config\"}\n" + + "public type ConnectionConfig record {|\n" + + " # The HTTP version understood by the client\n" + + " http:HttpVersion httpVersion = http:HTTP_1_1;\n" + + " # Configurations related to HTTP/1.x protocol\n" + + " ClientHttp1Settings http1Settings?;\n" + + " # Configurations related to HTTP/2 protocol\n" + + " http:ClientHttp2Settings http2Settings?;\n" + + " # The maximum time to wait (in seconds) for a response before closing the connection\n" + + " decimal timeout = 60;\n" + + " # The choice of setting `forwarded`/`x-forwarded` header\n" + + " string forwarded = \"disable\";\n" + + " # Configurations associated with request pooling\n" + + " http:PoolConfiguration poolConfig?;\n" + + " # HTTP caching related configurations\n" + + " http:CacheConfig cache?;\n" + + " # Specifies the way of handling compression (`accept-encoding`) header\n" + + " http:Compression compression = http:COMPRESSION_AUTO;\n" + + " # Configurations associated with the behaviour of the Circuit Breaker\n" + + " http:CircuitBreakerConfig circuitBreaker?;\n" + + " # Configurations associated with retrying\n" + + " http:RetryConfig retryConfig?;\n" + + " # Configurations associated with inbound response size limits\n" + + " http:ResponseLimitConfigs responseLimits?;\n" + + " # SSL/TLS-related options\n" + + " http:ClientSecureSocket secureSocket?;\n" + + " # Proxy server related options\n" + + " http:ProxyConfig proxy?;\n" + + " # Enables the inbound payload validation functionality which provided by the constraint package. " + + " Enabled by default\n" + + " boolean validation = true;\n" + + "|};"; } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestUtils.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestUtils.java index 11c13a2e0..ccc1d97e4 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestUtils.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestUtils.java @@ -20,10 +20,13 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.client.BallerinaClientGenerator; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.cmd.CmdUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; import io.ballerina.projects.Package; @@ -32,9 +35,10 @@ import io.ballerina.projects.ProjectKind; import io.ballerina.projects.directory.ProjectLoader; import io.ballerina.tools.diagnostics.Diagnostic; +import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.parser.OpenAPIV3Parser; -import io.swagger.v3.parser.core.models.SwaggerParseResult; +import io.swagger.v3.oas.models.SpecVersion; +import io.swagger.v3.oas.models.media.Schema; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; import org.testng.Assert; @@ -42,51 +46,84 @@ 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.ArrayList; -import java.util.Arrays; +import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIFromOpenAPIV3Parser; + /** * 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/generators/").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 Path servicePath = RES_DIR.resolve("ballerina_project/service.bal"); private static final String LINE_SEPARATOR = System.lineSeparator(); - List list1 = new ArrayList<>(); - List list2 = new ArrayList<>(); - Filter filter = new Filter(list1, list2); // Get diagnostics public static List getDiagnostics(SyntaxTree syntaxTree, OpenAPI openAPI, BallerinaClientGenerator ballerinaClientGenerator) throws FormatterException, IOException, BallerinaOpenApiException { - BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); - ballerinaSchemaGenerator.setTypeDefinitionNodeList(ballerinaClientGenerator.getTypeDefinitionNodeList()); + List preGeneratedTypeDefinitionNodes = new LinkedList<>(); + preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator. + getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + openAPI, false, preGeneratedTypeDefinitionNodes); SyntaxTree schemaSyntax = ballerinaSchemaGenerator.generateSyntaxTree(); SyntaxTree utilSyntaxTree = ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); - writeFile(clientPath, Formatter.format(syntaxTree).toString()); - writeFile(schemaPath, Formatter.format(schemaSyntax).toString()); - writeFile(utilPath, Formatter.format(utilSyntaxTree).toString()); + writeFile(clientPath, Formatter.format(syntaxTree).toSourceCode()); + writeFile(schemaPath, Formatter.format(schemaSyntax).toSourceCode()); + writeFile(utilPath, Formatter.format(utilSyntaxTree).toSourceCode()); SemanticModel semanticModel = getSemanticModel(clientPath); return semanticModel.diagnostics(); } public static List getDiagnostics(SyntaxTree syntaxTree) throws FormatterException, IOException { - writeFile(schemaPath, Formatter.format(syntaxTree).toString()); + writeFile(schemaPath, Formatter.format(syntaxTree).toSourceCode()); SemanticModel semanticModel = getSemanticModel(schemaPath); return semanticModel.diagnostics(); } + public static List getDiagnosticsForGenericService(SyntaxTree serviceSyntaxTree) + throws FormatterException, IOException { + writeFile(servicePath, Formatter.format(serviceSyntaxTree).toSourceCode()); + SemanticModel semanticModel = getSemanticModel(servicePath); + return semanticModel.diagnostics(); + } + + public static List getDiagnosticsForService(SyntaxTree serviceSyntaxTree, OpenAPI openAPI, + BallerinaServiceGenerator ballerinaServiceGenerator) + throws FormatterException, IOException, BallerinaOpenApiException { + List preGeneratedTypeDefNodes = new ArrayList<>( + ballerinaServiceGenerator.getTypeInclusionRecords()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + openAPI, false, preGeneratedTypeDefNodes); + String schemaContent = Formatter.format( + ballerinaSchemaGenerator.generateSyntaxTree()).toSourceCode(); + String serviceContent = Formatter.format(serviceSyntaxTree).toSourceCode(); + serviceContent = serviceContent.replaceAll( + "\\{" + System.lineSeparator() + "\\s*\\}", "\\{panic error(\"Tests\");\\}"); + writeFile(servicePath, serviceContent); + writeFile(schemaPath, schemaContent); + SemanticModel semanticModel = getSemanticModel(servicePath); + return semanticModel.diagnostics(); + } + //Get string as a content of ballerina file public static String getStringFromGivenBalFile(Path expectedServiceFile) throws IOException { Stream expectedServiceLines = Files.lines(expectedServiceFile); @@ -99,25 +136,19 @@ public static void compareGeneratedSyntaxTreeWithExpectedSyntaxTree(Path path, S throws IOException { String expectedBallerinaContent = getStringFromGivenBalFile(path); - String generatedSyntaxTree = syntaxTree.toString(); + String generatedSyntaxTree = syntaxTree.toSourceCode(); generatedSyntaxTree = generatedSyntaxTree.replaceAll(LINE_SEPARATOR, ""); generatedSyntaxTree = (generatedSyntaxTree.trim()).replaceAll("\\s+", ""); expectedBallerinaContent = (expectedBallerinaContent.trim()).replaceAll("\\s+", ""); - Assert.assertTrue(generatedSyntaxTree.equals(expectedBallerinaContent)); + Assert.assertEquals(expectedBallerinaContent, generatedSyntaxTree); } /* * Write the generated syntax tree to file. */ public static void writeFile(Path filePath, String content) throws IOException { - PrintWriter writer = null; - try { - writer = new PrintWriter(filePath.toString(), "UTF-8"); + try (PrintWriter writer = new PrintWriter(filePath.toString(), StandardCharsets.UTF_8)) { writer.print(content); - } finally { - if (writer != null) { - writer.close(); - } } } @@ -126,7 +157,7 @@ public static SemanticModel getSemanticModel(Path servicePath) { Project project = null; try { project = ProjectLoader.loadProject(servicePath); - } catch (ProjectException e) { + } catch (ProjectException ignored) { } Package packageName = project.currentPackage(); @@ -144,13 +175,10 @@ public static SemanticModel getSemanticModel(Path servicePath) { } public static OpenAPI getOpenAPI(Path definitionPath) throws IOException, BallerinaOpenApiException { - String openAPIFileContent = Files.readString(definitionPath); - SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(openAPIFileContent); - OpenAPI api = parseResult.getOpenAPI(); - return api; + return CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); } - public static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { + 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(); @@ -173,9 +201,8 @@ public static void compareGeneratedSyntaxTreewithExpectedSyntaxTree(String s, Sy public static void deleteGeneratedFiles() throws IOException { Path resourcesPath = RES_DIR.resolve("ballerina_project"); if (Files.exists(resourcesPath)) { - List listFiles = Arrays.asList( - Objects.requireNonNull(new File(String.valueOf(resourcesPath)).listFiles())); - for (File existsFile: listFiles) { + File[] listFiles = Objects.requireNonNull(new File(String.valueOf(resourcesPath)).listFiles()); + for (File existsFile : listFiles) { String fileName = existsFile.getName(); if (fileName.endsWith(".bal")) { existsFile.delete(); @@ -183,4 +210,42 @@ public static void deleteGeneratedFiles() throws IOException { } } } + + /** + * Normalized OpenAPI specification with adding proper naming to schema. + * + * @param openAPIPath - openAPI file path + * @return - openAPI specification + * @throws IOException + * @throws BallerinaOpenApiException + */ + public static OpenAPI normalizeOpenAPI(Path openAPIPath, boolean isClient, SpecVersion openAPIVersion) + throws IOException, + BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPIFromOpenAPIV3Parser(openAPIPath); + if (openAPIVersion.equals(SpecVersion.V31) && !openAPI.getSpecVersion().equals(SpecVersion.V31)) { + openAPI.setSpecVersion(SpecVersion.V31); + openAPI.setOpenapi("3.1.0"); + } + io.swagger.v3.oas.models.Paths openAPIPaths = openAPI.getPaths(); + if (isClient) { + GeneratorUtils.validateOperationIds(openAPIPaths.entrySet()); + } + GeneratorUtils.validateRequestBody(openAPIPaths.entrySet()); + + if (openAPI.getComponents() != null) { + // Refactor schema name with valid name + Components components = openAPI.getComponents(); + Map componentsSchemas = components.getSchemas(); + if (componentsSchemas != null) { + Map refacSchema = new HashMap<>(); + for (Map.Entry schemaEntry : componentsSchemas.entrySet()) { + String name = GeneratorUtils.getValidName(schemaEntry.getKey(), true); + refacSchema.put(name, schemaEntry.getValue()); + } + openAPI.getComponents().setSchemas(refacSchema); + } + } + return openAPI; + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/APIDocTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/APIDocTests.java index f8b8cdbf8..b43f9296b 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/APIDocTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/APIDocTests.java @@ -17,7 +17,6 @@ */ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -41,31 +40,31 @@ public void setup() throws IOException { } @Test(description = "Resource function api doc mapped to OAS operation summary") - public void testsForResourceFunction() throws OpenApiConverterException, IOException { + 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 OAS operation summary") - public void testsForPathParameter() throws OpenApiConverterException, IOException { + 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 OAS parameter description") - public void testsForQueryParameter() throws OpenApiConverterException, IOException { + 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 OAS requestBody description") - public void testsForRequestPayload() throws OpenApiConverterException, IOException { + public void testsForRequestPayload() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("apidoc/resource_function_with_requestbody_scenario.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/requestBody.yaml"); } @Test(description = "Record api doc mapped to OAS record description") - public void testsForRecord() throws OpenApiConverterException, IOException { + public void testsForRecord() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("apidoc/record.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/record.yaml"); } @@ -77,7 +76,7 @@ public void testsForRecordHasTypeInclusion() throws IOException { } @Test(description = "Reference scenarios") - public void testsForReferenceScenario() throws OpenApiConverterException, IOException { + public void testsForReferenceScenario() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("apidoc/reference_scenario.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/reference.yaml"); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/CacheConfigTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/CacheConfigTests.java index 1cc420f25..db8172ddd 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/CacheConfigTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/CacheConfigTests.java @@ -17,7 +17,6 @@ */ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -41,37 +40,37 @@ public void setup() throws IOException { } @Test(description = "Generate OpenAPI spec for service configuration annotation in resource without fields") - public void cacheConfigTests01() throws OpenApiConverterException, IOException { + public void cacheConfigTests01() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/configuration_rs01.yaml"); } @Test(description = "When cache-config has custom value without ETag and Last-Modified.") - public void cacheConfigTests02() throws OpenApiConverterException, IOException { + public void cacheConfigTests02() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs02.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/cache_config_02.yaml"); } @Test(description = "When cache-config has custom value with private field and no cache field enable") - public void cacheConfigTests03() throws OpenApiConverterException, IOException { + public void cacheConfigTests03() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs03.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/cache_config_03.yaml"); } @Test(description = "When cache-config has custom value with negative max age") - public void cacheConfigTests04() throws OpenApiConverterException, IOException { + public void cacheConfigTests04() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs04.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/cache_config_04.yaml"); } @Test(description = "When cache-config has custom value with negative max age") - public void cacheConfigTests05() throws OpenApiConverterException, IOException { + public void cacheConfigTests05() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs05.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/cache_config_05.yaml"); } @Test(description = "When cache-config has union type response with error") - public void cacheConfigTests06() throws OpenApiConverterException, IOException { + public void cacheConfigTests06() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/configuration_rs06.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/cache_config_06.yaml"); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/DataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/DataTypeTests.java index e05648efa..2adb42fab 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/DataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/DataTypeTests.java @@ -54,7 +54,7 @@ public void testForAllTypeDefinitionWithNullableValue() throws IOException { TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/nullable_type_def.yaml"); } - @Test(description = "test for tuple type scenarios", enabled = false) + @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 diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/EnumTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/EnumTypeTests.java index da5dff20b..859f43625 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/EnumTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/EnumTypeTests.java @@ -17,7 +17,6 @@ */ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -41,26 +40,48 @@ public void setup() throws IOException { this.tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); } @Test(description = "When the record field has reference to enum type") - public void testEnumType() throws OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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_type.yaml"); } - @Test(description = "When the record field has reference to enum with constant value") - public void testEnumWithConstantValue() throws OpenApiConverterException, IOException { + @Test(description = "Test for 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_value.yaml"); } + @Test(description = "Test for query and path parameters having references to enums with constant value") + public void testEnumsWithinQueryParameters() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/enum_query.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/enum_query.yaml"); + } + + @Test(description = "Test for header parameters having references to enums with constant values") + public void testEnumsWithinHeaderParameters() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/enum_header.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/enum_header.yaml"); + } + + //TODO:Enable this test after fixing issue : https://github.com/ballerina-platform/openapi-tools/issues/1472 + @Test(description = "Test for enum that defined as ballerina types", enabled = false) + public void testEnumsDefinedAsBalTypes() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/bal_type_enum.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/bal_type_enum.yaml"); + } + @AfterMethod public void cleanUp() { TestUtils.deleteDirectory(this.tempDir); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HeaderTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HeaderTests.java index 7d56bb14c..074f79b77 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HeaderTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HeaderTests.java @@ -18,7 +18,6 @@ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -42,63 +41,63 @@ public void setup() throws IOException { } @Test(description = "Generate OpenAPI spec with header type parameter") - public void testHeadscenario01() throws OpenApiConverterException, IOException { + public void testHeadscenario01() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario01.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario01.yaml"); } @Test(description = "Generate OpenAPI spec with header type parameter with annotation values") - public void testHeadersWithAnnotation() throws OpenApiConverterException, IOException { + public void testHeadersWithAnnotation() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario02.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario02.yaml"); } @Test(description = "Generate OpenAPI spec with header type parameter without curly brace") - public void testHeadersWithOutCurlyBrace() throws OpenApiConverterException, IOException { + public void testHeadersWithOutCurlyBrace() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario03.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario03.yaml"); } @Test(description = "Generate OpenAPI spec with for multiple headers") - public void testWithMultipleHeaders() throws OpenApiConverterException, IOException { + public void testWithMultipleHeaders() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario04.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario04.yaml"); } @Test(description = "Generate OpenAPI spec with for optional headers") - public void testOptionalHeaders() throws OpenApiConverterException, IOException { + public void testOptionalHeaders() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario05.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario05.yaml"); } @Test(description = "Generate OpenAPI spec with when the service config has nullable and optional enable field") - public void testHeadersWithAnnotations() throws OpenApiConverterException, IOException { + public void testHeadersWithAnnotations() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario06.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario06.yaml"); } @Test(description = "Generate OpenAPI spec when the header has defaultable parameter") - public void testHeadersWithDefaultValue() throws OpenApiConverterException, IOException { + public void testHeadersWithDefaultValue() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario07.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario07.yaml"); } @Test(description = "Generate OpenAPI spec when the header has defaultable parameter with nullable enable data " + "type") - public void testHeadersWithDefaultValueWithNullable() throws OpenApiConverterException, IOException { + public void testHeadersWithDefaultValueWithNullable() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario08.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario08.yaml"); } @Test(description = "Generate OpenAPI spec when the header has defaultable parameter with nullable enable data " + "type and service config enable") - public void testHeadersWithDefaultValueWithNullableServiceConfig() throws OpenApiConverterException, IOException { + public void testHeadersWithDefaultValueWithNullableServiceConfig() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario09.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario09.yaml"); } @Test(description = "Tests for header parameter has default value as expression") - public void testHeaderWithDefaultExpressionValue() throws OpenApiConverterException, IOException { + public void testHeaderWithDefaultExpressionValue() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("header_scenario10.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario10.yaml"); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HttpMethodTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HttpMethodTests.java index bef94209c..24e23cd5c 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HttpMethodTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/HttpMethodTests.java @@ -18,6 +18,7 @@ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import org.testng.Assert; import org.testng.annotations.AfterMethod; @@ -50,7 +51,7 @@ public void setup() throws IOException { @Test(description = "Compiler warning for 'default' resource methods.") public void testForCompilerWarningForDefault() { Path ballerinaFilePath = RES_DIR.resolve("default_bal.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null , false); List errors = openApiConverter.getErrors(); @@ -59,6 +60,18 @@ public void testForCompilerWarningForDefault() { "contain details for the `default` resource method in the Ballerina service."); } + @Test + public void testForPostMethodStatusCodeMapping() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("post_method.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "post_method.yaml"); + } + + @Test + public void testForResourceWithCatchAllPath() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("catch_all_path_service.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "catch_all_path_service.yaml"); + } + @AfterMethod public void cleanUp() { TestUtils.deleteDirectory(this.tempDir); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ListenerTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ListenerTests.java index 27707c08f..14a8baeb2 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ListenerTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ListenerTests.java @@ -17,7 +17,7 @@ */ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; +import io.ballerina.openapi.cmd.OASContractGenerator; import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import org.testng.Assert; import org.testng.annotations.AfterMethod; @@ -45,31 +45,31 @@ public void setup() throws IOException { } //Listeners @Test(description = "Generate OpenAPI spec for single listener") - public void testListeners01() throws OpenApiConverterException, IOException { + public void testListeners01() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario01.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario01.yaml"); } @Test(description = "Generate OpenAPI spec for listener only have port") - public void testListeners02() throws OpenApiConverterException, IOException { + public void testListeners02() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario02.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario02.yaml"); } @Test(description = "Generate OpenAPI spec for multiple listeners") - public void testListeners03() throws OpenApiConverterException, IOException { + public void testListeners03() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario03.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario03.yaml"); } @Test(description = "Generate OpenAPI spec for ExplicitNewExpressionNode listeners") - public void testListeners04() throws OpenApiConverterException, IOException { + public void testListeners04() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario04.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario04.yaml"); } @Test(description = "Generate OpenAPI spec for multiple listeners") - public void testListeners05() throws OpenApiConverterException, IOException { + public void testListeners05() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario05.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario05.yaml"); } @@ -77,7 +77,7 @@ public void testListeners05() throws OpenApiConverterException, IOException { @Test(description = "When given ballerina file contain some compilation issue.") public void testListeners06() { Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario06.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null , false); List errors = openApiConverter.getErrors(); @@ -85,7 +85,7 @@ public void testListeners06() { } @Test(description = "Generate OpenAPI spec for http load balancer listeners") - public void testListeners07() throws OpenApiConverterException, IOException { + 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"); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ModuleReferenceTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ModuleReferenceTests.java index 4dfe44487..ede75ddcc 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ModuleReferenceTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ModuleReferenceTests.java @@ -66,4 +66,28 @@ public void testResponse06() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response_annotation.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/response_annotation.yaml"); } + + @Test + public void testRecordReferenceWithReadOnly() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("readonly.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "readonly.yaml"); + } + + @Test (enabled = false) + public void testListenersInSeparateModule() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners_in_separate_module.bal"); + String osName = System.getProperty("os.name"); + String yamlFile = osName.toLowerCase().contains("windows") ? "windows_listeners_in_separate_module.yaml" + : "listeners_in_separate_module.yaml"; + TestUtils.compareWithGeneratedFile(ballerinaFilePath, yamlFile); + } + + @Test (enabled = false) + public void testListenersInSeparateFiles() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners_in_separate_file.bal"); + String osName = System.getProperty("os.name"); + String yamlFile = osName.toLowerCase().contains("windows") ? "windows_listeners_in_separate_file.yaml" + : "listeners_in_separate_file.yaml"; + TestUtils.compareWithGeneratedFile(ballerinaFilePath, yamlFile); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/OpenApiConverterUtilsTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/OpenApiConverterUtilsTest.java index 0516fee4f..1f7922c6d 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/OpenApiConverterUtilsTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/OpenApiConverterUtilsTest.java @@ -18,6 +18,7 @@ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -50,7 +51,7 @@ public void setup() throws IOException { @Test(description = "Generate OpenAPI spec") public void testBasicServices() { Path ballerinaFilePath = RES_DIR.resolve("basic_service.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); @@ -61,19 +62,19 @@ public void testBasicServices() { @Test(description = "Generate OpenAPI spec by filtering non existing service") public void testBasicServicesWithInvalidServiceName() { Path ballerinaFilePath = RES_DIR.resolve("basic_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, "/abc", false); Assert.assertFalse(openApiConverter.getErrors().isEmpty()); - Assert.assertEquals(openApiConverter.getErrors().get(0).getMessage(), "No Ballerina services found " + - "with name '/abc' to generate an OpenAPI specification. These services are available in " + - "ballerina file. [/hello, /hello02]"); + Assert.assertEquals(openApiConverter.getErrors().get(0).getMessage(), + "No Ballerina HTTP services found with name '/abc' to generate an OpenAPI specification. " + + "These services are available in ballerina file. [/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("basic_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); @@ -84,7 +85,7 @@ public void testIfExampleSetFlagContains() throws IOException { @Test(description = "Generate OpenAPI spec by filtering service name") public void testBasicServicesByFiltering() { Path ballerinaFilePath = RES_DIR.resolve("basic_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, "/hello02", false); @@ -95,7 +96,7 @@ public void testBasicServicesByFiltering() { @Test(description = "Generate OpenAPI spec with complex base paths") public void testComplexBasePathServices() { Path ballerinaFilePath = RES_DIR.resolve("complex_base_path.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); @@ -106,7 +107,7 @@ public void testComplexBasePathServices() { @Test(description = "Generate OpenAPI spec with no base path") public void testServicesWithNoBasePath() { Path ballerinaFilePath = RES_DIR.resolve("no_base_path_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); Assert.assertTrue(Files.exists(this.tempDir.resolve("no_base_path_service_openapi.yaml"))); @@ -115,7 +116,7 @@ public void testServicesWithNoBasePath() { @Test(description = "Generate OpenAPI spec with no base path") public void testServicesWithNoBasePathWithFilterina() { Path ballerinaFilePath = RES_DIR.resolve("no_base_path_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, "/", false); Assert.assertTrue(Files.exists(this.tempDir.resolve("no_base_path_service_openapi.yaml"))); @@ -148,7 +149,7 @@ public void testPathscenario04() throws IOException { @Test(description = "Generate OpenAPI spec for build project") public void testRecordFieldPayLoad() { Path ballerinaFilePath = RES_DIR.resolve("project_bal/record_payload_service.bal"); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); Assert.assertTrue(Files.exists(this.tempDir.resolve("payloadV_openapi.yaml"))); @@ -175,7 +176,7 @@ public void testForCompilerWarning() throws IOException { @Test(description = "Test for non http services") public void testForNonHttpServices() { Path ballerinaFilePath = RES_DIR.resolve("non_service.bal"); - new OpenApiConverter().generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null + new OASContractGenerator().generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null , false); Assert.assertTrue(!Files.exists(tempDir.resolve("query_openapi.yaml"))); } @@ -185,7 +186,7 @@ public void testForRemovingEscapeIdentifier() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("escape_identifier.bal"); Path tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); try { - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null , false); if (Files.exists(tempDir.resolve("v1_abc_hello_openapi.yaml"))) { diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ParameterAnnotationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ParameterAnnotationTests.java new file mode 100644 index 000000000..78d538589 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ParameterAnnotationTests.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.generators.openapi; + +import io.ballerina.openapi.cmd.OASContractGenerator; +import org.testng.Assert; +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.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class is for capturing the scenarios with parameter annotations in resource methods. + */ +public class ParameterAnnotationTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/ballerina-to-openapi").toAbsolutePath(); + private Path tempDir; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @Test(description = "Test OpenAPI generation when payload is not annotated") + public void testPayloadNotAnnotated() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("parameter_annotation/unannotated_payload.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "parameter_annotation/unannotated_payload.yaml"); + } + + @Test(description = "Test OpenAPI generation for complex scenarios with annotated payload") + public void testComplexAnnotatedPayload() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("parameter_annotation/annotated_payload_complex.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "parameter_annotation/annotated_payload_complex.yaml"); + } + + @Test(description = "Test OpenAPI generation when query parameter is annotated") + public void testQueryParameterAnnotated() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("parameter_annotation/annotated_query.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "parameter_annotation/annotated_query.yaml"); + } + + @Test(description = "Test OpenAPI generation when invalid parameters") + public void testInvalidParameters() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("parameter_annotation/invalid_payload.bal"); + Path tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); + Assert.assertTrue(Files.notExists(tempDir.resolve("payloadV_openapi.yaml")), + "OpenAPI file is generated for a bal file with errors due to invalid " + + "resource function parameters."); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/QueryParameterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/QueryParameterTests.java index 40230b4c9..4a04ee27a 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/QueryParameterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/QueryParameterTests.java @@ -18,7 +18,6 @@ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -45,50 +44,50 @@ public void setup() throws IOException { // public type QueryParamType json | () |BasicType|BasicType[]; @Test(description = "Required query parameter") - public void testQueryScenario01() throws OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + public void testQueryscenario04() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario04.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario04.yaml"); } @Test(description = "Query parameter has service config with optional field false") - public void testQueryscenario05() throws OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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)", enabled = false) - public void testQueryscenario07() throws OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + public void testQueryscenario08() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario08.bal"); TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario08.yaml"); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RecordTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RecordTests.java index 2707e3544..90ceb50cf 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RecordTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RecordTests.java @@ -17,7 +17,6 @@ */ package io.ballerina.openapi.generators.openapi; -import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; @@ -32,6 +31,7 @@ * 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/ballerina-to-openapi").toAbsolutePath(); private Path tempDir; @@ -39,53 +39,54 @@ public class RecordTests { public void setup() throws IOException { this.tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); } + @Test(description = "When the record field has typeInclusion it map to allOfSchema in OAS") - public void testTypeInclusion() throws OpenApiConverterException, IOException { + 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 OAS") - public void testRequiredField() throws OpenApiConverterException, IOException { + 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 OAS") - public void testNullableFieldWithOptional() throws OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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 OpenApiConverterException, IOException { + 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", - enabled = false) - public void testUnionTypeWithNullable() throws OpenApiConverterException, IOException { + @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.yaml"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/union_with_nullable.yaml"); } @Test(description = "When the record field has cyclic record type") @@ -100,6 +101,24 @@ public void testReadOnlyRecord() throws IOException { TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/with_read_only_keyword.yaml"); } + @Test(description = "Test for records having cyclic dependencies and same record inclusions") + public void testRecordsWithCyclicDependenciesIncludingSameTypeInclusion() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/cyclic_record_with_typeInclusion.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/cyclic_record_with_typeInclusion.yaml"); + } + + @Test(description = "Test for record type definitions with interdependencies") + public void testInterdependenceRecordWithTypeRef() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/typeref_records_with_interdependency.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/typeref_records_with_interdependency.yaml"); + } + + @Test(description = "Test for union type with interdependent record members") + public void testInterdependenceRecordWithUnionType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/union_records_with_interdependency.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/union_records_with_interdependency.yaml"); + } + @AfterMethod public void cleanUp() { TestUtils.deleteDirectory(this.tempDir); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RequestBodyTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RequestBodyTest.java index 358e55749..c7306a645 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RequestBodyTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/RequestBodyTest.java @@ -18,6 +18,7 @@ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import io.ballerina.openapi.converter.OpenApiConverterException; import org.testng.Assert; import org.testng.annotations.AfterMethod; @@ -57,7 +58,7 @@ public void testJsonPayLoad() throws OpenApiConverterException { @Test(description = "Generate OpenAPI spec with xml payload") public void testXmlPayLoad() { Path ballerinaFilePath = RES_DIR.resolve("request_body/xml_payload_service.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null, false); Assert.assertTrue(Files.exists(this.tempDir.resolve("payloadXml_openapi.yaml"))); @@ -200,7 +201,7 @@ public void testServiceConfig() { @Test(description = "Generate OpenAPI spec for request body with http:Request req") public void testRequestBodyWithDefault() { Path ballerinaFilePath = RES_DIR.resolve("request_body/rb_scenario13.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); @@ -210,7 +211,7 @@ public void testRequestBodyWithDefault() { @Test(description = "Generate OpenAPI spec for GET method having a request body") public void testRequestBodyWithGETMethod() { Path ballerinaFilePath = RES_DIR.resolve("request_body/rb_scenario14.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); Assert.assertFalse(openApiConverterUtils.getErrors().isEmpty()); @@ -223,7 +224,7 @@ public void testRequestBodyWithGETMethod() { @Test(description = "Generate OpenAPI spec for request body having map type") public void testRequestBodyWithMapString() { Path ballerinaFilePath = RES_DIR.resolve("request_body/rb_scenario15.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); @@ -235,7 +236,7 @@ public void testNestedRecordPayLoadJson() { try { String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("expected_gen/json"), "nestedRecord.json"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); if (Files.exists(this.tempDir.resolve("payloadV_openapi.json"))) { @@ -253,6 +254,16 @@ public void testNestedRecordPayLoadJson() { } } + @Test(description = "When the service has config without mediaType attribute") + public void testForServiceConfigOnlyWithCors() { + Path ballerinaFilePath = RES_DIR.resolve("request_body/service_config_with_cors.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , true); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "service_config_with_cors.yaml"); + } + @AfterMethod public void cleanUp() { deleteDirectory(this.tempDir); @@ -291,7 +302,7 @@ private void compareWithGeneratedFile(Path ballerinaFilePath, String yamlFile) { String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("expected_gen/request_body"), yamlFile); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); if (Files.exists(this.tempDir.resolve("payloadV_openapi.yaml"))) { diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ResponseTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ResponseTests.java index 5e2c28333..2916d3f6f 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ResponseTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ResponseTests.java @@ -17,6 +17,7 @@ */ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -28,6 +29,9 @@ import java.nio.file.Path; import java.nio.file.Paths; +import static io.ballerina.openapi.generators.common.TestUtils.getStringFromGivenBalFile; +import static io.ballerina.openapi.generators.openapi.TestUtils.compareWithGeneratedFile; + /** * This test class for the covering the unit tests for return type scenarios. */ @@ -43,212 +47,330 @@ public void setup() throws IOException { @Test(description = "Response scenario01 without return type") public void testResponse01() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario01.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario01.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario01.yaml"); } @Test(description = "Response scenario02 without return type") public void testResponse02() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario02.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario02.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario02.yaml"); } @Test(description = "Response scenario03 - return type with Record") public void testResponse03() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario03.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario03.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario03.yaml"); } @Test(description = "Response scenario 04 - Response has multiple responses without content type") public void testResponse04() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario04.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario04.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario04.yaml"); } @Test(description = "Response scenario 05 - Error response with a schema", enabled = false) public void testResponse05() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("rs_scenario05.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "rs_scenario05.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "rs_scenario05.yaml"); } @Test(description = "Response scenario 06 - Error response with a schema", enabled = false) public void testResponse06() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario06.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario06.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario06.yaml"); } @Test(description = "Response scenario 09 - return has record, error, basic types") public void testResponse09() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario09.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario09.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario09.yaml"); } @Test(description = "Response scenario 10 - Array type response with a schema") public void testResponse10() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario10.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario10.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario10.yaml"); } @Test(description = "When the return type is record with typeInclusion field of http code ") public void testTypeInclusion() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/typeInclusion_01.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/typeInclusion_01.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/typeInclusion_01.yaml"); } @Test(description = "When the return type is string") public void testStringReturn() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario11.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario11.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario11.yaml"); } @Test(description = "When the return type is inline record") public void testInlineRecordReturn() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario12.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario12.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario12.yaml"); } @Test(description = "When the return type is inline record") public void testInlineRecordHasHttpTypeInclusion() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario13.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario13.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario13.yaml"); } @Test(description = "When the return type is inline record", enabled = false) public void testInlineRecordHasReference() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario14.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario14.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario14.yaml"); } @Test(description = "When the return type is inline record with non http typeInclusion fields", enabled = false) public void testInlineRecordHasTypeInclusionReference() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario16.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario16.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario16.yaml"); } @Test(description = "When the return type is array record ") public void testArrayRecord() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/array_record.bal"); //Compare generated yaml file with expected yaml content - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/array_record.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/array_record.yaml"); } @Test(description = "Generate OpenAPI spec for service configuration annotation in resource") public void testWithAnnotation() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario17.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario17.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario17.yaml"); } - @Test(description = "Generate OpenAPI spec for service configuration annotation in resource") + @Test(description = "Generate OpenAPI spec for resource function which has service configuration annotation " + + "including details with vendor specific media type") public void testWithAnnotationForAllType() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario18.bal"); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario18.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario18.yaml"); } @Test(description = "Test for return type has `http:Response`.") public void testHttpResponse() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario19.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario19.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario19.yaml"); } @Test(description = "Test for return type has `http:Response|error?`.") public void testUnionHttpResponse() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario20.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , true); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario20.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario20.yaml"); } @Test(description = "Test for return type having form value content.") public void urlEncodeResponse() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_with_url_encode.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_url_encode.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_url_encode.yaml"); } @Test(description = "When the response has payload annotation") public void responseHasPayload() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_with_payload.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_payload.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_payload.yaml"); } @Test(description = "When the response has payload annotation and service config annotation") public void responseHasPayloadWithServiceConfig() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_with_payload_service_config.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_payload_service_config.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_payload_service_config.yaml"); } @Test(description = "When the response has payload annotation with custom media type and " + "service config annotation") public void responseWithCustomMediaType() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/rs_with_service_and_payload_annotation.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, + compareWithGeneratedFile(ballerinaFilePath, "response/rs_with_service_and_payload_annotation.yaml"); } @Test(description = "When the response has all the status codes") public void testForAllReturnType() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/response_code.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/response_code.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/response_code.yaml"); } @Test(description = "When the response has return record without no body field") public void testForNoContentReturnCode() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/without_body_field.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/no_body_field.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/no_body_field.yaml"); } @Test(description = "When the response has float return type") public void testResponseWithFloatReturnType() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/float.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/float.yaml"); + compareWithGeneratedFile(ballerinaFilePath, "response/float.yaml"); } @Test(description = "When the response has decimal return type") public void testResponseWithDecimalReturnType() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("response/decimal.bal"); - OpenApiConverter openApiConverterUtils = new OpenApiConverter(); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/decimal.yaml"); + } + + @Test(description = "When the response has byte[] return type") + public void testResponseWithByteArray() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/byte.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/byte.yaml"); + } + + @Test + public void testWithMultipleReturnPayloadSameStatusCode() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/same_status_code.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/same_status_code.yaml"); + } + + @Test(description = "Test scenarios where return type is a SimpleNameReference") + public void testResponseWithSimpleNameReferenceReturnType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/simple_name_ref.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/simple_name_ref.yaml"); + } + + @Test(description = "Test scenarios where return type is a SimpleNameReference with readonly") + public void testResponseWithReadOnlySimpleNameReferenceReturnType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/readonly.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/readonly.yaml"); + } + + @Test(description = "Test scenarios where return type is a deprecated status code 'NetworkAuthorizationRequired'") + public void testUsingDeprecatedStatusCode() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/deprecated_status_code.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + + compareWithGeneratedFile(ballerinaFilePath, "response/deprecated_status_code.yaml"); + } + + @Test(description = "When the service has config without mediaType attribute") + public void testResponseHasServiceConfigWithCors() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/service_config_with_cors.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/service_config_with_cors.yaml"); + } + + @Test(description = "When the service has `error` and `InternalServerError`") + public void testForResponseHasSameErrorStatusCode() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/service_with_error_and_internal_server_error.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/service_with_error_and_internal_server_error.yaml"); + } + + @Test(description = "When the service has same error response code") + public void testForResponseHasSameStatusCode() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/service_with_same_status_codes.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + compareWithGeneratedFile(ballerinaFilePath, "response/service_with_same_status_code.yaml"); + } + + @Test(description = "When the service has config without mediaType attribute, and with slash path") + public void testResponseHasServiceConfigWithCorsWithSlash() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/service_config_with_cors_with_slash.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); + openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null + , false); + Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("expected_gen"), + "response/service_config_with_cors_with_slash.yaml"); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); + String generatedYaml = getStringFromGivenBalFile(tempDir, + "service_config_with_cors_with_slash_openapi.yaml"); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); + } + + @Test(description = "When the service has config without mediaType attribute, and without base path") + public void testResponseHasServiceConfigWithCorsWithoutBasePath() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/service_config_with_cors_without_base_path.bal"); + OASContractGenerator openApiConverterUtils = new OASContractGenerator(); openApiConverterUtils.generateOAS3DefinitionsAllService(ballerinaFilePath, this.tempDir, null , false); Assert.assertTrue(openApiConverterUtils.getErrors().isEmpty()); - TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/decimal.yaml"); + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("expected_gen"), + "response/service_config_with_cors_without_base_path.yaml"); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); + String generatedYaml = getStringFromGivenBalFile(tempDir, + "service_config_with_cors_without_base_path_openapi.yaml"); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); } @AfterMethod diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java index 92378158a..97c6126eb 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java @@ -17,6 +17,7 @@ */ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -87,7 +88,7 @@ private void executeMethod(Path ballerinaFilePath, String yamlFile, String gener try { String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("openapi"), yamlFile); - OpenApiConverter openApiConverter = new OpenApiConverter(); + OASContractGenerator openApiConverter = new OASContractGenerator(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); if (Files.exists(tempDir.resolve(generatedYamlFile)) && findFile(tempDir, secondGeneratedFile) != null) { diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/TestUtils.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/TestUtils.java index fc7befd62..50ce2b4c6 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/TestUtils.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/TestUtils.java @@ -17,6 +17,7 @@ */ package io.ballerina.openapi.generators.openapi; +import io.ballerina.openapi.cmd.OASContractGenerator; import org.testng.Assert; import java.io.File; @@ -32,6 +33,7 @@ * This Util class for storing the common utils related to test in ballerina to openAPI command implementation. */ public class TestUtils { + private static final Path RES_DIR = Paths.get("src/test/resources/ballerina-to-openapi/").toAbsolutePath(); private static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { @@ -40,6 +42,7 @@ private static String getStringFromGivenBalFile(Path expectedServiceFile, String expectedServiceLines.close(); return expectedServiceContent; } + public static void deleteGeneratedFiles(String filename, Path tempDir) { try { Files.deleteIfExists(tempDir.resolve(filename)); @@ -48,14 +51,12 @@ public static void deleteGeneratedFiles(String filename, Path tempDir) { } } - public static void compareWithGeneratedFile(Path ballerinaFilePath, String yamlFile) - throws IOException { + public static void compareWithGeneratedFile(Path ballerinaFilePath, String yamlFile) throws IOException { Path tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); try { String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("expected_gen"), yamlFile); - OpenApiConverter openApiConverter = new OpenApiConverter(); - openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null - , false); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); if (Files.exists(tempDir.resolve("payloadV_openapi.yaml"))) { String generatedYaml = getStringFromGivenBalFile(tempDir, "payloadV_openapi.yaml"); generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); @@ -72,15 +73,17 @@ public static void compareWithGeneratedFile(Path ballerinaFilePath, String yamlF System.gc(); } } + public static void deleteDirectory(Path path) { - try { - if (Files.exists(path)) { - Files.walk(path) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } catch (IOException e) { + 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/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/UnSupportedBallerinaFileTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/UnSupportedBallerinaFileTests.java new file mode 100644 index 000000000..fb9017fc1 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/UnSupportedBallerinaFileTests.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.generators.openapi; + +import io.ballerina.openapi.cmd.OASContractGenerator; +import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; +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.ByteArrayOutputStream; +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 class tests the tool behaviour in OpenAPI contract generation when unsupported Ballerina file is given. + */ +public class UnSupportedBallerinaFileTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/ballerina-to-openapi/").toAbsolutePath(); + private Path tempDir; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @Test(description = "Test the warning message when unsupported bal file with graphql service is given") + public void testCompilerWarningForUnsupportedGraphQLService() { + Path ballerinaFilePath = RES_DIR.resolve("graphql_service.bal"); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null + , false); + List errors = openApiConverter.getErrors(); + Assert.assertFalse(errors.isEmpty(), "Error list is empty"); + Assert.assertEquals(errors.get(0).getMessage(), + "Given Ballerina file does not contain any HTTP service."); + } + + @Test(description = "Test the warning message when unsupported bal file with main function is given") + public void testCompilerWarningForUnsupportedBallerinaFile() { + Path ballerinaFilePath = RES_DIR.resolve("unsupported_main_file.bal"); + OASContractGenerator openApiConverter = new OASContractGenerator(); + openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null + , false); + List errors = openApiConverter.getErrors(); + Assert.assertFalse(errors.isEmpty()); + Assert.assertEquals(errors.get(0).getMessage(), + "Given Ballerina file does not contain any HTTP service."); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + System.gc(); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AdvanceRecordTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AdvanceRecordTypeTests.java index ae74c8cae..a51c350f0 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AdvanceRecordTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AdvanceRecordTypeTests.java @@ -21,8 +21,9 @@ import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; @@ -42,14 +43,13 @@ public class AdvanceRecordTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); // Enable after adding `not` data bind support @Test(description = "Generate record for schema has not type", enabled = false) public void generateSchemaHasNotType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario10.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema10.bal", syntaxTree); @@ -59,7 +59,7 @@ public void generateSchemaHasNotType() throws IOException, BallerinaOpenApiExcep public void generateSchemaHasInlineRecord() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario11.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema11.bal", syntaxTree); @@ -69,7 +69,7 @@ public void generateSchemaHasInlineRecord() throws IOException, BallerinaOpenApi public void generateOpenAPIWeatherAPI() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/openapi_weather_api.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/openapi_weather_api_schema.bal", syntaxTree); @@ -78,7 +78,7 @@ public void generateOpenAPIWeatherAPI() throws IOException, BallerinaOpenApiExce @Test(description = "Generate record for schema has object type only") public void generateForSchemaHasObjectTypeOnly() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario14.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); Schema schema = openAPI.getComponents().getSchemas().get("Error"); ObjectSchema objectSchema = (ObjectSchema) schema; BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AllOfDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AllOfDataTypeTests.java index 6bf264e93..1b9590d96 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AllOfDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AllOfDataTypeTests.java @@ -19,8 +19,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -35,12 +36,11 @@ public class AllOfDataTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Generate record for schema has allOf reference") public void generateAllOf() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario09.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema09.bal", syntaxTree); @@ -49,7 +49,7 @@ public void generateAllOf() throws IOException, BallerinaOpenApiException { @Test(description = "Generate record for schema has allOf reference in record field") public void generateAllOfInRecordField() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/allOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/allOf.bal", syntaxTree); @@ -58,7 +58,7 @@ public void generateAllOfInRecordField() throws IOException, BallerinaOpenApiExc @Test(description = "Generate record when allOf schema has only one references schema") public void generateTypeForSingleAllOfSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/allOf_with_one_ref.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -69,7 +69,7 @@ public void generateTypeForSingleAllOfSchema() throws IOException, BallerinaOpen "schema") public void generateCyclicSchemaAllOfSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/allOf_with_cyclic.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -79,7 +79,7 @@ public void generateCyclicSchemaAllOfSchema() throws IOException, BallerinaOpenA @Test(description = "Generate record for allOf schema with array schema") public void generateAllOfWithTypeUnSpecifiedObjectSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/allOfWithNoType.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/allOfWithNoType.bal", syntaxTree); @@ -88,7 +88,7 @@ public void generateAllOfWithTypeUnSpecifiedObjectSchema() throws IOException, B @Test(description = "Generate record for allOf type array schemas with inline object schemas") public void generateArrayAllOfInlineObjects() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_with_inline_allOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -98,7 +98,7 @@ public void generateArrayAllOfInlineObjects() throws IOException, BallerinaOpenA @Test(description = "Generate record for allOf schema with empty object schema") public void generateAllOfWithEmptyObjectSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/allOfWithEmptyObject.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -108,11 +108,10 @@ public void generateAllOfWithEmptyObjectSchema() throws IOException, BallerinaOp @Test(description = "Generate record for nested allOf schemas") public void generateNestedAllOfSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/nested_allOf_with_allOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); - TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( - "schema/ballerina/nested_all_of.bal", syntaxTree); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/nested_all_of.bal", syntaxTree); } @Test(description = "Tests record generation for nested OneOf schema inside AllOf schema", @@ -121,7 +120,7 @@ public void generateNestedAllOfSchema() throws IOException, BallerinaOpenApiExce "Unsupported nested OneOf or AnyOf schema is found inside a AllOf schema.") public void arrayHasMaxItemsExceedLimit02() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/nested_allOf_with_oneOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnnotationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnnotationTests.java index b05900691..7e23f5b42 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnnotationTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnnotationTests.java @@ -1,8 +1,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -17,12 +18,11 @@ public class AnnotationTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Generate records with deprecated annotation") public void generateRecordsWithDeprecatedAnnotations() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/deprecated_schemas.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnyOfDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnyOfDataTypeTests.java index d18b82213..f90528493 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnyOfDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/AnyOfDataTypeTests.java @@ -19,9 +19,11 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Schema; @@ -31,28 +33,26 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.List; import static io.ballerina.openapi.generators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; /** - * All the tests related to AnyDataType handling the - * {@link io.ballerina.openapi.generators.client.BallerinaClientGenerator} util. + * Test implementation to verify the `anyOf` property related scenarios in openAPI schema generation, handled by + * the {@link BallerinaTypesGenerator}. */ public class AnyOfDataTypeTests { - private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); + private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); @Test(description = "Test for the schema has anyOf dataType") public void testAnyOfInSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario15.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - Schema schema = openAPI.getComponents().getSchemas().get("AnyOF"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + Schema schema = openAPI.getComponents().getSchemas().get("AnyOF"); ComposedSchema composedSchema = (ComposedSchema) schema; - List anyOf = composedSchema.getAnyOf(); - GeneratorMetaData.createInstance(openAPI, false); - String anyOfUnionType = TypeGeneratorUtils.getUnionType(anyOf, "AnyOF").toString().trim(); + GeneratorMetaData.createInstance(openAPI, false, false); + UnionTypeGenerator unionTypeGenerator = new UnionTypeGenerator(composedSchema, "AnyOF"); + String anyOfUnionType = unionTypeGenerator.generateTypeDescriptorNode().toString().trim(); Assert.assertEquals(anyOfUnionType, "User|Activity"); } @@ -60,7 +60,7 @@ public void testAnyOfInSchema() throws IOException, BallerinaOpenApiException { public void testAnyOfSchema() throws BallerinaOpenApiException, IOException { Path definitionPath = RES_DIR.resolve("swagger/scenario15.yaml"); Path expectedPath = RES_DIR.resolve("ballerina/schema15.bal"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ArrayDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ArrayDataTypeTests.java index 072e3335f..0b6544d27 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ArrayDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ArrayDataTypeTests.java @@ -18,8 +18,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.AfterMethod; @@ -38,7 +39,6 @@ public class ArrayDataTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); private final PrintStream originalStdOut = System.out; private ByteArrayOutputStream consoleContent = new ByteArrayOutputStream(); @@ -51,7 +51,7 @@ public void beforeTest() { @Test(description = "Generate record with array filed record") public void generateRecordWithArrayField() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario03.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema03.bal", syntaxTree); @@ -60,7 +60,7 @@ public void generateRecordWithArrayField() throws IOException, BallerinaOpenApiE @Test(description = "Scenario04-Generate record with nested array filed record") public void generateScenario04() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario04.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema04.bal", syntaxTree); @@ -69,7 +69,7 @@ public void generateScenario04() throws IOException, BallerinaOpenApiException { @Test(description = "Generate record with record type array filed record") public void generateRecordWithRecordArrayField() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario06.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema06.bal", syntaxTree); @@ -79,7 +79,7 @@ public void generateRecordWithRecordArrayField() throws IOException, BallerinaOp @Test(description = "Generate record for schema has array reference") public void generateSchemaHasArrayReference() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario08.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema08.bal", syntaxTree); @@ -88,7 +88,7 @@ public void generateSchemaHasArrayReference() throws IOException, BallerinaOpenA @Test(description = "Generate Array for schema has array reference") public void generateSchemaArrayReference() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/schema_with_array.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema_with_array.bal", @@ -98,7 +98,7 @@ public void generateSchemaArrayReference() throws IOException, BallerinaOpenApiE @Test(description = "Generate Array for schema has array reference") public void generateSchemaNestedArrayReference() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/schema_with_nested_array.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema_with_nested_array.bal", @@ -108,7 +108,7 @@ public void generateSchemaNestedArrayReference() throws IOException, BallerinaOp @Test(description = "Array schema has no data type in items") public void arrayNoDatatype() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_no_item_type.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/array_no_item_type.bal", @@ -118,7 +118,7 @@ public void arrayNoDatatype() throws IOException, BallerinaOpenApiException { @Test(description = "Array schema has max item count") public void arrayHasMaxItems() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_max_item.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/array_max_item.bal", @@ -128,7 +128,7 @@ public void arrayHasMaxItems() throws IOException, BallerinaOpenApiException { @Test(description = "Array schema with allOf") public void arrayHasAllOfItems() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_with_allOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/array_with_allOf.bal", @@ -138,7 +138,7 @@ public void arrayHasAllOfItems() throws IOException, BallerinaOpenApiException { @Test(description = "Array schema with oneOf") public void arrayHasOneOFfItems() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_with_oneOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/array_with_oneOf.bal", @@ -148,7 +148,7 @@ public void arrayHasOneOFfItems() throws IOException, BallerinaOpenApiException @Test(description = "Array schema with oneOf schema with nullable item") public void arrayHasOneOfItemsWithNullable() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_with_oneOf_complex.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -160,7 +160,7 @@ public void arrayHasOneOfItemsWithNullable() throws IOException, BallerinaOpenAp expectedExceptionsMessageRegExp = "Maximum item count defined in the definition exceeds the.*") public void arrayHasMaxItemsExceedLimit() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_exceed_max_item.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); } @@ -170,7 +170,7 @@ public void arrayHasMaxItemsExceedLimit() throws IOException, BallerinaOpenApiEx expectedExceptionsMessageRegExp = "Maximum item count defined in the definition exceeds the.*") public void arrayHasMaxItemsExceedLimit02() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/array_exceed_max_item_02.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ConstraintTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ConstraintTests.java index 5cf02265a..f574e20d6 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ConstraintTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ConstraintTests.java @@ -18,14 +18,17 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.FormatterException; -import org.testng.Assert; -import org.testng.annotations.AfterTest; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; @@ -34,24 +37,32 @@ import java.util.List; import static io.ballerina.openapi.generators.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/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); + + @BeforeMethod + public void setUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } + @Test(description = "Tests with record field has constraint and record field type can be user defined datatype " + "with constraint.") public void testRecordFiledConstraint() throws IOException, BallerinaOpenApiException, FormatterException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/record_field.yaml"), true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/record_field.yaml"), + true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/constraint/record_field.bal", syntaxTree); List diagnostics = getDiagnostics(syntaxTree); - Assert.assertTrue(diagnostics.isEmpty()); + assertTrue(diagnostics.isEmpty()); } @Test(description = "Tests for all the array type scenarios:" + @@ -61,13 +72,13 @@ public void testRecordFiledConstraint() throws IOException, BallerinaOpenApiExce "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, BallerinaOpenApiException, FormatterException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/array.yaml"), true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/array.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/constraint/array.bal", syntaxTree); List diagnostics = getDiagnostics(syntaxTree); - Assert.assertTrue(diagnostics.isEmpty()); + assertTrue(diagnostics.isEmpty()); } @Test(description = "Tests for the field has reference type scenarios" + @@ -75,21 +86,179 @@ public void testForArray() throws IOException, BallerinaOpenApiException, Format "Use case 02 : Annotations on a type" + "Use case 03 : Annotations on a type used as a record field") public void testForReference() throws IOException, BallerinaOpenApiException, FormatterException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/type_def_node.yaml"), + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/type_def_node.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/constraint/type_def_node.bal", syntaxTree); List diagnostics = getDiagnostics(syntaxTree); - Assert.assertTrue(diagnostics.isEmpty()); + assertTrue(diagnostics.isEmpty()); } - @AfterTest - public void cleanUp() throws IOException { - TestUtils.deleteGeneratedFiles(); + + @Test(description = "Tests with record field has constraint value with zero.") + public void testRecordFiledConstraintWithZeroValue() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint/record_field_02.yaml"), + true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/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, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/nested_array_with_constraint.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/constraint/nested_array.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Tests with additional properties field has constraint.") + public void testAdditionalPropertiesWithConstraint() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/additional_properties_with_constraint.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/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. + + @Test(description = "Test for invalid constraint value") + public void testInvalidConstraintUses() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/invalidConstraintFieldWithDataType.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/invalidConstraintFieldWithDtaType.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Test for invalid constraint value with valid constraint value") + public void testInvalidAndValidBothConstraintUses() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/invalidAndValidConstraintFieldWithDataType.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/invalidAndValidConstraintFieldWithDtaType.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Test for allowing zero value for number and integer type") + public void testAllowedZeroValuesForNumber() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/allow_zero_values_for_number_constraint.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/allow_zero_values_for_number_constraint.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Tests for nullable reference types with constraint.") + public void testNullableRefTypesWithConstraint() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/constraint_with_nullable.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/constraint_with_nullable.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Test for schema properties having pattern constraint.") + public void testStringSchemaPropertyWithPattern() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/pattern_string.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/string_pattern.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Test for exclusiveMin and exclusiveMax property changes in OpenAPI 3.1") + public void testExclusiveMinMaxInV31() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/exclusive_min_max_3_1.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/exclusive_min_max_3_1.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test(description = "Test for schema properties containing data types with format constraints.") + public void testDataTypeHasFormatWithConstraint() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/format_types_v3_0.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/format_type.bal", syntaxTree); + + //Test for OpenAPI version 3.1 + OpenAPI openAPIV31 = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/format_types_v3_1.yaml"), true); + BallerinaTypesGenerator schemaGenerator = new BallerinaTypesGenerator(openAPIV31); + SyntaxTree syntaxTreeV3 = schemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/format_type.bal", syntaxTreeV3); + } + + @AfterMethod + private void deleteGeneratedFiles() { + try { + TestUtils.deleteGeneratedFiles(); + } catch (IOException ignored) { + } + } + + @AfterClass + public void cleanUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/EnumGenerationTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/EnumGenerationTests.java new file mode 100644 index 000000000..16b681d49 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/EnumGenerationTests.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * 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.openapi.generators.schema; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.generators.common.TestUtils; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.swagger.v3.oas.models.OpenAPI; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +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.openapi.generators.common.TestUtils.getDiagnostics; +import static org.testng.Assert.assertTrue; + +/** + * Test cases for generating ballerina types for enum schemas. + */ +public class EnumGenerationTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); + + @BeforeTest + public void setUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } + + @Test(description = "Tests for all the enum scenarios in schema generation:" + + "Use case 01 : Reusable enum" + + "Use case 02 : Enums in schema properties" + + "Use case 03 : Enum with null value" + + "Use case 04 : Enum as array items") + public void testForEnums() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/schema_with_enums.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema_with_enums.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Tests for all the enum scenarios in schema generation:" + + "Use case 01 : Nullable reusable enum" + + "Use case 02 : Nullable integer enum" + + "Use case 03 : Nullable boolean enum" + + "Use case 04 : Nullable float enum" + + "Use case 05 : Nullable enum in arrays") + public void testForNullableEnums() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve( + "swagger/schema_with_nullable_enums.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema_with_nullable_enums.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Test enum with no values") + public void testForEmptyEnums() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve( + "swagger/empty_enum.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/empty_enum.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + @AfterTest + private void deleteGeneratedFiles() { + try { + TestUtils.deleteGeneratedFiles(); + } catch (IOException ignored) { + } + } + + @AfterClass + public void cleanUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/FieldGenWithNullableOption.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/FieldGenWithNullableOption.java index 6486ca336..6eace00a5 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/FieldGenWithNullableOption.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/FieldGenWithNullableOption.java @@ -18,8 +18,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; @@ -34,11 +35,10 @@ */ public class FieldGenWithNullableOption { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Test for nullable primitive fields") public void testNullablePrimitive() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_option_primitive_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -48,7 +48,7 @@ public void testNullablePrimitive() throws IOException, BallerinaOpenApiExceptio @Test(description = "Test for nullable array fields") public void testNullableArray() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_option_array_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -58,7 +58,7 @@ public void testNullableArray() throws IOException, BallerinaOpenApiException { @Test(description = "Test for nullable record fields") public void testNullableRecord() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_option_record_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -68,7 +68,7 @@ public void testNullableRecord() throws IOException, BallerinaOpenApiException { @Test(description = "Test for primitive referenced type") public void testPrimitiveReferencedTypes() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_option_string_type.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -79,7 +79,7 @@ public void testPrimitiveReferencedTypes() throws IOException, BallerinaOpenApiE @Test(description = "Test for referenced schema with no type given") public void testNullTypeReference() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_option_null_type.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -89,7 +89,7 @@ public void testNullTypeReference() throws IOException, BallerinaOpenApiExceptio @Test(description = "Test field generation when nullable false") public void testNullableFalse() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_false.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/IntegerDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/IntegerDataTypeTests.java new file mode 100644 index 000000000..7a0cd0f38 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/IntegerDataTypeTests.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * 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.openapi.generators.schema; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.generators.common.TestUtils; +import io.swagger.v3.oas.models.OpenAPI; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Test class for testing integer data types int32 and int64. + */ +public class IntegerDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); + + @DataProvider(name = "intTestData") + public Object[][] intFormatTestData() { + return new Object[][]{ + {"swagger/schema_integer_signed32.yaml", "schema/ballerina/schema_integer_signed32.bal"}, + {"swagger/schema_integer_signed32_ref.yaml", "schema/ballerina/schema_integer_signed32_ref.bal"}, + {"swagger/schema_integer_signed64.yaml", "schema/ballerina/schema_integer_signed64.bal"}, + {"swagger/schema_integer_invalid_format.yaml", "schema/ballerina/schema_integer_invalid_format.bal"}, + {"swagger/schema_integer_array.yaml", "schema/ballerina/schema_integer_array.bal"}, + }; + } + + @Test(dataProvider = "intTestData", description = "Tests valid schema integer value formats") + public void testIntegerFormatTypeSchema(final String swaggerPath, final String balPath) + throws IOException, BallerinaOpenApiException { + + final Path definitionPath = RES_DIR.resolve(swaggerPath); + final OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + final BallerinaTypesGenerator ballerinaTypesGenerator = new BallerinaTypesGenerator(openAPI); + final SyntaxTree syntaxTree = ballerinaTypesGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree(balPath, syntaxTree); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaNegativeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaNegativeTests.java new file mode 100644 index 000000000..05df46536 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaNegativeTests.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.openapi.generators.schema; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.generators.common.TestUtils; +import io.swagger.v3.oas.models.OpenAPI; +import org.ballerinalang.formatter.core.FormatterException; +import org.junit.After; +import org.junit.Before; +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; + +/** + * This class is for containing the negative tests related to the {@code MapSchema}. + */ +public class MapSchemaNegativeTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); + private ByteArrayOutputStream output = new ByteArrayOutputStream(); + + + @Before + public void setUp() { + System.setErr(new PrintStream(output)); + } + + @Test(expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "OpenAPI definition has errors: \n" + + "attribute components.schemas.User02.additionalProperties.*") + public void testForAdditionalPropertiesWithParserIssue() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/additional_properties_true_negative.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } + + @Test + public void testForAdditionalPropertiesWithoutParserIssue() + throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/additional_properties_true_negative_without_parser_issue.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + // Check the generated content, till the warning test enable. + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/additional_properties_negative.bal", syntaxTree); + + String expectedOut = "WARNING: constraints in the OpenAPI contract will be ignored for the " + + "additionalProperties field, as constraints are not supported on Ballerina rest record field.\n" + + "WARNING: generating Ballerina rest record field will be ignored for the OpenAPI contract " + + "additionalProperties type `ComposedSchema`, as it is not supported on Ballerina rest record field."; +// Assert.assertTrue(output.toString().contains(expectedOut)); + } + + @After + public void tearDown() { + output = new ByteArrayOutputStream(); + System.setErr(new PrintStream(output)); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaTests.java new file mode 100644 index 000000000..1136df379 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/MapSchemaTests.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.openapi.generators.schema; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.generators.common.TestUtils; +import io.swagger.v3.oas.models.OpenAPI; +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/generators/schema").toAbsolutePath(); + + @Test + public void testForAdditionalProperties() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/additional_properties_true.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/additional_properties_true.bal", syntaxTree); + } + + @Test + public void testForAdditionalPropertiesComposedSchema() + throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/additional_properties_composed_schema.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, true); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/additional_properties_composed_schema.bal", syntaxTree); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NegativeConstraintTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NegativeConstraintTests.java new file mode 100644 index 000000000..5b6d06f25 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NegativeConstraintTests.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. + * + * 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.openapi.generators.schema; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.generators.common.TestUtils; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.swagger.v3.oas.models.OpenAPI; +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.openapi.generators.common.TestUtils.getDiagnostics; +import static org.testng.Assert.assertFalse; + +/** + * This test class contains negative tests related to constraint validation. + */ +public class NegativeConstraintTests { + private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); + + @Test(description = "Tests for non-string type record field has invalid pattern constraint." + + "There is no pattern validation within swagger parser although swagger support for only string value to " + + "have regular pattern" + + "(https://swagger.io/docs/specification/data-models/data-types/#string:~:text=The%20pattern%20keyword%20)" + + "Therefore, code generation for patterns with non-string types is silently ignored here. This will be" + + " handled in a separate PR in the future.") + public void testNonStringSchemaPropertyWithPattern() throws IOException, BallerinaOpenApiException, + FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/constraint" + + "/pattern_except_string_type.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/constraint/pattern_except_string_type.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NestedRecordInclusionTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NestedRecordInclusionTests.java index c97631643..a35969062 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NestedRecordInclusionTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NestedRecordInclusionTests.java @@ -1,8 +1,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -17,12 +18,11 @@ public class NestedRecordInclusionTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Generate records for nested referenced schemas") public void generateAllOf() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/nested_schema_refs.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NullableFieldTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NullableFieldTests.java index d897742fa..1bdcfcf6e 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NullableFieldTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/NullableFieldTests.java @@ -19,10 +19,12 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; +import org.ballerinalang.formatter.core.FormatterException; import org.testng.Assert; import org.testng.annotations.Test; @@ -35,11 +37,10 @@ */ public class NullableFieldTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Test for nullable primitive fields") public void testNullablePrimitive() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_primitive_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -49,7 +50,7 @@ public void testNullablePrimitive() throws IOException, BallerinaOpenApiExceptio @Test(description = "Test for nullable array fields") public void testNullableArray() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_array_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -59,7 +60,7 @@ public void testNullableArray() throws IOException, BallerinaOpenApiException { @Test(description = "Test for nullable array referenced schemas") public void testNullableArrayRefSchemas() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_ref_array.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -69,7 +70,7 @@ public void testNullableArrayRefSchemas() throws IOException, BallerinaOpenApiEx @Test(description = "Test nullable for primitive referenced type") public void testPrimitiveReferencedTypes() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_string_type.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -80,7 +81,7 @@ public void testPrimitiveReferencedTypes() throws IOException, BallerinaOpenApiE @Test(description = "Test for referenced schema with no type given") public void testNullTypeReference() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_null_type.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -90,7 +91,7 @@ public void testNullTypeReference() throws IOException, BallerinaOpenApiExceptio @Test(description = "Test for nullable record fields") public void testNullableRecord() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_record_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -99,8 +100,8 @@ public void testNullableRecord() throws IOException, BallerinaOpenApiException { } @Test(description = "Test for union type generation for nullable anyOf schema") - public void testNullableUnionType() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + public void testNullableUnionType() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_anyof_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -109,12 +110,32 @@ public void testNullableUnionType() throws IOException, BallerinaOpenApiExceptio } @Test(description = "Test for union type generation for nullable anyOf schema with array schema") - public void testNullableArrayUnionType() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + public void testNullableArrayUnionType() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/nullable_anyof_array_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/" + "nullable_anyof_array_schema.bal", syntaxTree); } + + @Test(description = "Test for type generation for object schema with no properties") + public void testNullableEmptyObjectSchema() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/null_empty_record.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/" + + "null_empty_record.bal", syntaxTree); + } + + @Test(description = "Test for type generation for OpenAPI 3.1 schemas with `null` type") + public void testNullTypePropertyGeneration() throws IOException, BallerinaOpenApiException, FormatterException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/null_type_3_1.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/" + + "null_type_3_1.bal", syntaxTree); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/OneOfDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/OneOfDataTypeTests.java index 569f0cdce..3ebc01cc6 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/OneOfDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/OneOfDataTypeTests.java @@ -19,11 +19,14 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.TypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.ballerina.openapi.generators.common.TestUtils; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.TypeGenerator; -import io.ballerina.openapi.generators.schema.model.GeneratorMetaData; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Schema; @@ -33,47 +36,46 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.List; /** - * All the tests related to OneOF data binding handling the {@link BallerinaTypesGenerator} - * util. + * Test implementation to verify the `oneOf` property related scenarios in openAPI schema generation, handled by + * the {@link BallerinaTypesGenerator}. */ public class OneOfDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Generate record for schema has oneOF") public void generateForSchemaHasOneOf() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/scenario12.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - Schema schema = openAPI.getComponents().getSchemas().get("Error"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + Schema schema = openAPI.getComponents().getSchemas().get("Error"); ComposedSchema composedSchema = (ComposedSchema) schema; - List oneOf = composedSchema.getOneOf(); - GeneratorMetaData.createInstance(openAPI, false); - String oneOfUnionType = TypeGeneratorUtils.getUnionType(oneOf, "Error").toString().trim(); + GeneratorMetaData.createInstance(openAPI, false, false); + UnionTypeGenerator unionTypeGenerator = new UnionTypeGenerator(composedSchema, "Error"); + String oneOfUnionType = unionTypeGenerator.generateTypeDescriptorNode().toString().trim(); + Assert.assertEquals(oneOfUnionType, "Activity|Profile"); } @Test(description = "Generate record for schema has object type with OneOf") public void generateForSchemaObjectType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/scenario13.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - Schema schema = openAPI.getComponents().getSchemas().get("Error"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + Schema schema = openAPI.getComponents().getSchemas().get("Error"); ComposedSchema composedSchema = (ComposedSchema) schema; - List oneOf = composedSchema.getOneOf(); - GeneratorMetaData.createInstance(openAPI, false); - String oneOfUnionType = TypeGeneratorUtils.getUnionType(oneOf, "Error").toString().trim(); + GeneratorMetaData.createInstance(openAPI, false, false); + UnionTypeGenerator unionTypeGenerator = new UnionTypeGenerator(composedSchema, "Error"); + String oneOfUnionType = unionTypeGenerator.generateTypeDescriptorNode().toString().trim(); Assert.assertEquals(oneOfUnionType, "Activity|Profile01"); } @Test(description = "Generate union type when nullable is true") public void generateUnionTypeWhenNullableTrue() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/scenario12.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - Schema schema = openAPI.getComponents().getSchemas().get("Error"); - ComposedSchema composedSchema = (ComposedSchema) schema; - GeneratorMetaData.createInstance(openAPI, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + Schema schema = openAPI.getComponents().getSchemas().get("Error"); + GeneratorMetaData.createInstance(openAPI, true, false); TypeGenerator typeGenerator = TypeGeneratorUtils.getTypeGenerator(schema, "Error", null); String oneOfUnionType = typeGenerator.generateTypeDescriptorNode().toString().trim(); Assert.assertEquals(oneOfUnionType, "Activity|Profile?"); @@ -82,7 +84,7 @@ public void generateUnionTypeWhenNullableTrue() throws IOException, BallerinaOpe @Test(description = "Tests full schema genrations with oneOf type") public void generateOneOFTests() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/oneOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/oneOf.bal", syntaxTree); @@ -91,7 +93,7 @@ public void generateOneOFTests() throws IOException, BallerinaOpenApiException { @Test(description = "Tests record generation for oneOf schemas with inline object schemas") public void oneOfWithInlineObject() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/oneOf_with_inline_schemas.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( @@ -101,7 +103,7 @@ public void oneOfWithInlineObject() throws IOException, BallerinaOpenApiExceptio @Test(description = "Tests record generation for nested OneOf schema inside AllOf schema") public void oneOfWithNestedAllOf() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("generators/schema/swagger/nested_oneOf_with_allOf.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/PrimitiveDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/PrimitiveDataTypeTests.java index 5457be293..5bd9c2445 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/PrimitiveDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/PrimitiveDataTypeTests.java @@ -19,8 +19,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.Assert; @@ -41,7 +42,6 @@ public class PrimitiveDataTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); private SyntaxTree syntaxTree; private ByteArrayOutputStream outContent; - CodeGenerator codeGenerator = new CodeGenerator(); @BeforeTest public void setUp() { @@ -52,7 +52,7 @@ public void setUp() { @Test(description = "Generate single record") public void generateScenario01() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario01.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema01.bal", syntaxTree); @@ -61,7 +61,7 @@ public void generateScenario01() throws IOException, BallerinaOpenApiException { @Test(description = "Generate multiple record") public void generateScenario02() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario02.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema02.bal", syntaxTree); @@ -70,11 +70,11 @@ public void generateScenario02() throws IOException, BallerinaOpenApiException { @Test(description = "Scenario for missing DataType") public void generateMissingDatatype() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/missDataType.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); - String expected = "public type Pet record { #this is missing dataType anydata id; string name; decimal tag?; " + - "string 'type?;};"; + String expected = "public type Pet record { #this is missing dataType anydata id; string name; decimal tag?;" + + " string 'type?;};"; Assert.assertTrue(syntaxTree.toString().trim().replaceAll("\\s+", ""). contains(expected.trim().replaceAll("\\s+", ""))); } @@ -82,13 +82,34 @@ public void generateMissingDatatype() throws IOException, BallerinaOpenApiExcept @Test(description = "When the component schema has primitive data type instead of object schema") public void generateSchemaForPrimitiveData() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/schema_with_primitive.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema_with_primitive.bal", syntaxTree); } + @Test(description = "Test for unsupported primitive type additional properties") + public void generateSchemaForInvalidAdditionalProperty() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/additional_properties_invalid_format.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/" + + "additional_properties_invalid_format.bal", + syntaxTree); + } + + @Test(description = "Test for primitive types with formats") + public void generateSchemaForPrimitiveTypesWithUnsupportedFormats() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/invalid_formats.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/invalid_formats.bal", syntaxTree); + } + @AfterTest public void clean() { System.setErr(null); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDataTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDataTypeTests.java index d9adbb020..278e8bfbc 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDataTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDataTypeTests.java @@ -19,8 +19,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -35,12 +36,11 @@ public class RecordDataTypeTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); SyntaxTree syntaxTree; - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Generate record with record type filed record") public void generateRecordWithRecordField() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario05.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema05.bal", syntaxTree); @@ -49,7 +49,7 @@ public void generateRecordWithRecordField() throws IOException, BallerinaOpenApi @Test(description = "Generate record with nested record type filed record") public void generateNestedRecord() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/scenario07.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/schema07.bal", syntaxTree); @@ -58,7 +58,7 @@ public void generateNestedRecord() throws IOException, BallerinaOpenApiException @Test(description = "Generate empty record when no properties are given") public void generateEmptyRecord() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/empty_record.yaml"); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("schema/ballerina/empty_record.bal", syntaxTree); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDefaultValueTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDefaultValueTests.java index a3d6c4450..9ebad2a9a 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDefaultValueTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/RecordDefaultValueTests.java @@ -19,8 +19,9 @@ package io.ballerina.openapi.generators.schema; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -34,11 +35,10 @@ */ public class RecordDefaultValueTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Test for default optional primitive fields in records") public void testDefaultPrimitive() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/default_optional_primitive_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -48,7 +48,7 @@ public void testDefaultPrimitive() throws IOException, BallerinaOpenApiException @Test(description = "Test for default optional String fields in records") public void testDefaultString() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/default_optional_string_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -58,7 +58,7 @@ public void testDefaultString() throws IOException, BallerinaOpenApiException { @Test(description = "Test for default optional String fields with value double quote in records") public void testDefaultWithDoubleQuote() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/default_optional_schema_with_doublequote.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -68,7 +68,7 @@ public void testDefaultWithDoubleQuote() throws IOException, BallerinaOpenApiExc @Test(description = "Test for default value for array record") public void testDefaultArray() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/default_optional_array_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -78,7 +78,7 @@ public void testDefaultArray() throws IOException, BallerinaOpenApiException { @Test(description = "Test for default value for required fields") public void testDefaultRequired() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/default_required_field_schema.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ReferenceResolveTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ReferenceResolveTests.java index 8b90d052a..e458b3736 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ReferenceResolveTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/ReferenceResolveTests.java @@ -17,9 +17,13 @@ */ package io.ballerina.openapi.generators.schema; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.FunctionSignatureGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.openapi.generators.common.TestUtils; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -27,17 +31,17 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; - +import java.util.ArrayList; +import java.util.List; /** * Tests for Schema Reference resolve. */ public class ReferenceResolveTests { private static final Path RES_DIR = Paths.get("src/test/resources/generators/schema").toAbsolutePath(); - CodeGenerator codeGenerator = new CodeGenerator(); @Test(description = "Tests with object type include reference") public void testReferenceIncludeWithObjectType() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger/world_bank.yaml"), true); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/world_bank.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -46,7 +50,7 @@ public void testReferenceIncludeWithObjectType() throws IOException, BallerinaOp @Test(description = "Test for object data type when absent reference and properties fields") public void testWorldBank() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/object_without_fields_reference.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); @@ -56,7 +60,7 @@ public void testWorldBank() throws IOException, BallerinaOpenApiException { } @Test(description = "Test for type generation for query parameters with referenced schemas") public void testParameterSchemaReferences() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/schema_referenced_in_parameters.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); @@ -67,7 +71,7 @@ public void testParameterSchemaReferences() throws IOException, BallerinaOpenApi @Test(description = "Test Ballerina types generation when referred by another record with no additional fields") public void testReferredTypesWithoutAdditionalFields() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/referred_inclusion.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -77,7 +81,7 @@ public void testReferredTypesWithoutAdditionalFields() throws IOException, Balle @Test(description = "Test doc comment generation of record fields when property is reffered to another schema") public void testDocCommentResolvingForRefferedSchemas() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger" + + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + "/resolve_reference_docs.yaml"), true); BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); @@ -85,12 +89,22 @@ public void testDocCommentResolvingForRefferedSchemas() throws IOException, Ball "schema/ballerina/resolve_reference_docs.bal", syntaxTree); } - @Test(description = "Test swagger file has undocumented reference in schema.", - expectedExceptions = BallerinaOpenApiException.class, - expectedExceptionsMessageRegExp = "Undefined \\$ref: '#/components/schemas/Person01' in openAPI.*") - public void testForUndocumentedReference() throws IOException, BallerinaOpenApiException { - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(RES_DIR.resolve("swagger/undocument_ref.yaml"), true); - BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + @Test(description = "Test for type generation for request body with reference") + public void testRequestBodyReferences() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger" + + "/request_body_with_ref.yaml"), true); + FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(openAPI, + new BallerinaTypesGenerator(openAPI), new ArrayList<>(), false); + FunctionSignatureNode signature1 = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/pets").getPost(), new ArrayList<>()); + FunctionSignatureNode signature2 = functionSignatureGenerator.getFunctionSignatureNode(openAPI.getPaths() + .get("/pets/dogs").getPost(), new ArrayList<>()); + List preGeneratedTypeDefNodes = new ArrayList<>( + functionSignatureGenerator.getTypeDefinitionNodeList()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, + false, preGeneratedTypeDefNodes); SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "schema/ballerina/schema_with_request_body_ref.bal", syntaxTree); } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/SwaggerFileParserTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/SwaggerFileParserTests.java index 81f6c5c20..c5ba93061 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/SwaggerFileParserTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/schema/SwaggerFileParserTests.java @@ -18,8 +18,10 @@ package io.ballerina.openapi.generators.schema; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -53,4 +55,14 @@ public void testInvalidFileType() throws IOException, BallerinaOpenApiException public void testInvalidFile() throws IOException, BallerinaOpenApiException { OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(RES_DIR.resolve("swagger/invalid.yaml")); } + + @Test(description = "Test swagger file has undocumented reference in schema.", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "OpenAPI definition has errors: \n" + + "attribute components.schemas.Person.Person01 is not of type `schema`.*") + public void testForUndocumentedReference() throws IOException, BallerinaOpenApiException { + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(RES_DIR.resolve("swagger/undocument_ref.yaml"), true); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderParameterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderParameterTests.java index 7ffb970f5..62a93c6f6 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderParameterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderParameterTests.java @@ -18,9 +18,11 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.testng.annotations.Test; @@ -44,7 +46,11 @@ public class HeaderParameterTests { public void requiredHeader() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_01.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_01.bal", syntaxTree); } @@ -55,21 +61,26 @@ public void requiredHeader() throws IOException, BallerinaOpenApiException { public void requiredHeaderWithNoHeaderType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_02.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header.bal", syntaxTree); } - @Test(description = "03. Header parameter with unsupported header data type", - expectedExceptions = BallerinaOpenApiException.class, - expectedExceptionsMessageRegExp = "Header 'x-request-id' with type 'integer' can not be mapped" + - " as a valid Ballerina.*") + @Test(description = "03. Header parameter with integer header data type") public void headerWithNoSupportType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_03.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); - CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header.bal", syntaxTree); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_03.bal", syntaxTree); } @Test(description = "04. Header parameter with array type with no item type", @@ -79,28 +90,37 @@ public void headerWithNoSupportType() throws IOException, BallerinaOpenApiExcept public void headerNoItemType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_04.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header.bal", syntaxTree); } - @Test(description = "05. Header parameter has array type with not support item type", - expectedExceptions = BallerinaOpenApiException.class, - expectedExceptionsMessageRegExp = "Header 'x-request-id' with array item type: 'integer' is not" + - " supported.*") + @Test(description = "05. Header parameter has array type with integer item type") public void headerNoSupportArrayItemType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_05.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); - CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header.bal", syntaxTree); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_05.bal", syntaxTree); } @Test(description = "06. Optional header parameter") public void optionalHeaders() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_06.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_06.bal", syntaxTree); } @@ -109,7 +129,11 @@ public void optionalHeaders() throws IOException, BallerinaOpenApiException { public void optionalHeadersWithArray() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_07.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_07.bal", syntaxTree); } @@ -118,7 +142,11 @@ public void optionalHeadersWithArray() throws IOException, BallerinaOpenApiExcep public void optionalHeadersWithArrayDefaultValue() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_08.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_08.bal", syntaxTree); } @@ -127,7 +155,11 @@ public void optionalHeadersWithArrayDefaultValue() throws IOException, Ballerina public void optionalHeadersWithDefaultValue() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_09.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_09.bal", syntaxTree); } @@ -136,7 +168,11 @@ public void optionalHeadersWithDefaultValue() throws IOException, BallerinaOpenA public void requiredNullableTrue() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_10.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_10.bal", syntaxTree); } @@ -145,7 +181,11 @@ public void requiredNullableTrue() throws IOException, BallerinaOpenApiException public void optionalHeaderWithNullableTrue() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_11.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_11.bal", syntaxTree); } @@ -154,8 +194,101 @@ public void optionalHeaderWithNullableTrue() throws IOException, BallerinaOpenAp public void paramterOrder() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/headers/header_12.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_12.bal", syntaxTree); } + + @Test(description = "13. Header parameters with references") + public void parametersWithReferences() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/headers_with_reference.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "headers/header_with_reference.bal", syntaxTree); + } + + @Test(description = "14. Header parameter with invalid reference", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Header 'X-User' with type 'object' can not be " + + "mapped as a valid Ballerina header parameter.*") + public void parametersWithInvalidReferences() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/header_with_invalid_ref.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "15. Header parameter with invalid array reference with record type", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Header 'X-Users' with array item type: 'User'" + + " is not supported in Ballerina.*") + public void parametersWithInvalidarrayReferences() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/header_with_invalid_array_ref.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "16. Header parameter with invalid type (object)", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Header 'X-User' with type 'object' can not be mapped as a " + + "valid Ballerina header parameter.*") + public void parametersWithInvalidInlineObjectType() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/header_record_type.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "17. Header parameter with invalid array type (object)", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Header 'X-User' with array item type: 'object' " + + "is not supported in Ballerina.*") + public void parametersWithInvalidObjectTypeArray() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/header_with_invalid_object.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "18. Header parameter with invalid type (empty object)", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Header 'X-User' with type 'object' can not be mapped " + + "as a valid Ballerina header parameter.*") + public void parametersWithInvalidEmptyObjectType() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/headers/header_with_invalid_type.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderTests.java index 6a33a25fb..b35d01e36 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/HeaderTests.java @@ -18,10 +18,13 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; @@ -40,16 +43,30 @@ public class HeaderTests { List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); Filter filter = new Filter(list1, list2); - SyntaxTree syntaxTree; + + @DataProvider(name = "intHeaderTestData") + public Object[][] intFormatTestData() { + return new Object[][]{ + {"generators/service/swagger/headers/multiHeaderParam.yaml", "headers/header_parameters.bal"}, + {"generators/service/swagger/headers/header_integer_signed32.yaml", + "headers/header_integer_signed32.bal"}, + {"generators/service/swagger/headers/header_integer_invalid.yaml", + "headers/header_integer_invalid.bal"}, + }; + } //Scenario 03 - Header parameters. - @Test(description = "Generate functionDefinitionNode for Header parameters") - public void generateHeaderParameter() throws IOException, BallerinaOpenApiException { - Path definitionPath = RES_DIR.resolve("generators/service/swagger/headers/multiHeaderParam.yaml"); + @Test(dataProvider = "intHeaderTestData", description = "Generate functionDefinitionNode for Header parameters") + public void generateHeaderParameter(final String swaggerPath, final String balPath) + throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve(swaggerPath); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); - syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); - CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("headers/header_parameters.bal", - syntaxTree); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + final SyntaxTree syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree(balPath, syntaxTree); } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ListenerTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ListenerTests.java index effaabf82..393fc42c4 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ListenerTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ListenerTests.java @@ -19,9 +19,11 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.cmd.CmdUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; @@ -46,8 +48,12 @@ public class ListenerTests { @Test(description = "Generate importors") public void generateImports() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("generators/service/swagger/listeners/petstore_listeners.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("listeners/importors.bal", syntaxTree); } @@ -56,8 +62,12 @@ public void generateImports() throws IOException, BallerinaOpenApiException, For expectedExceptionsMessageRegExp = "Failed to read endpoint details of the server: /v1") public void generatelisteners() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("generators/service/swagger/listeners/petstore_listeners02.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("listeners/listeners.bal", syntaxTree); } @@ -65,8 +75,12 @@ public void generatelisteners() throws IOException, BallerinaOpenApiException, F @Test(description = "Generate listeners") public void generatelisteners02() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("generators/service/swagger/listeners/petstore_listeners03.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("listeners/listeners03.bal", syntaxTree); } @@ -74,8 +88,12 @@ public void generatelisteners02() throws IOException, BallerinaOpenApiException, @Test(description = "Generate listeners when the server url is there and variables are absent") public void generatelisteners03() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("generators/service/swagger/listeners/petstore_listeners04.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("listeners/listeners04.bal", syntaxTree); } @@ -83,8 +101,12 @@ public void generatelisteners03() throws IOException, BallerinaOpenApiException, @Test(description = "Generate listeners when the server url base path is absent") public void generatelisteners04() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("generators/service/swagger/listeners/petstore_listeners05.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("listeners/listeners05.bal", syntaxTree); } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ParameterGeneratorTest.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ParameterGeneratorTest.java index 7a43983ef..f196e0489 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ParameterGeneratorTest.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ParameterGeneratorTest.java @@ -19,9 +19,11 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; @@ -47,7 +49,11 @@ public class ParameterGeneratorTest { public void generateService() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("swagger/petstore_service.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("service_gen.bal", syntaxTree); } @@ -56,7 +62,11 @@ public void generateService() throws IOException, BallerinaOpenApiException, For public void generateServiceWithPathSpecialCharacters() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/petstore_service_with_special_characters.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("service_gen_special_characters.bal", syntaxTree); @@ -66,16 +76,24 @@ public void generateServiceWithPathSpecialCharacters() throws IOException, Balle public void generateMultipleOperations() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiOperations.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("multi_operations.bal", syntaxTree); } @Test(description = "Generate functionDefinitionNode for multiple paths") - public void generateMultiplePath() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateMultiplePath() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiPaths.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("multi_paths.bal", syntaxTree); } @@ -85,7 +103,11 @@ public void generateMultiplePath() throws IOException, BallerinaOpenApiException public void generatePathParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiPathParam.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("path_parameters.bal", syntaxTree); } @@ -95,7 +117,11 @@ public void generatePathParameter() throws IOException, BallerinaOpenApiExceptio public void generatePathParameter02() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiPathParam02.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("path_parameters02.bal", syntaxTree); } @@ -104,7 +130,11 @@ public void generatePathParameter02() throws IOException, BallerinaOpenApiExcept public void generatePathParameter03() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiPathParam03.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("path_parameters03.bal", syntaxTree); } @@ -116,7 +146,11 @@ public void generatePathParameter03() throws IOException, BallerinaOpenApiExcept public void generateQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/multiQueryParam.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query_parameters.bal", syntaxTree); @@ -124,12 +158,17 @@ public void generateQueryParameter() throws IOException, BallerinaOpenApiExcepti @Test(description = "Generate functionDefinitionNode for paramter for content instead of schema", expectedExceptions = BallerinaOpenApiException.class, - expectedExceptionsMessageRegExp = "Query parameters with type 'content' can not be mapped to the " + - "Ballerina query.*") + expectedExceptionsMessageRegExp = "Type 'json' is not a valid query parameter type in Ballerina. " + + "The supported types are string, int, float, boolean, decimal, " + + "array types of the aforementioned types and map.") public void generateParameterHasContent() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/parameterTypehasContent.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("param_type_with_content.bal", syntaxTree); } @@ -138,8 +177,90 @@ public void generateParameterHasContent() throws IOException, BallerinaOpenApiEx public void withKeyWords() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/keywords.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("keywords.bal", syntaxTree); } + + @Test(description = "Tests for all the enum scenarios in resource function parameter generation:" + + "Use case 01 : Enum in query parameter" + + "Use case 02 : Enums in path parameter" + + "Use case 03 : Enum in header parameter" + + "Use case 04 : Enum in reusable parameter" + + "Use case 05 : Enum in parameter with referenced schema") + public void generateParametersWithEnums() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_enum.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("parameters_with_enum.bal", syntaxTree); + } + + @Test(description = "Tests for all the nullable enum scenarios in resource function parameter generation:" + + "Use case 01 : Nullable enum in query parameter" + + "Use case 02 : Nullable enum in header parameter" + + "Use case 03 : Nullable enum in reusable parameter" + + "Use case 04 : Nullable enum in parameter with referenced schema") + public void generateParametersWithNullableEnums() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_nullable_enums.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "parameters_with_nullable_enums.bal", syntaxTree); + } + + @Test(description = "Test unsupported nullable path parameter with enums", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Path parameter value cannot be null.") + public void testNullablePathParamWithEnum() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/path_param_nullable.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "Tests int32, int64, and invalid integer path parameters") + public void testsIntegerPathParameters() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/intPathParam.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("intPathParam.bal", syntaxTree); + } + + @Test(description = "Tests for referenced parameters in OpenAPI 3.1 version specs") + public void testsRefParamsInOpenAPIV31() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameter_with_ref_v31.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "parameter_with_ref_v31.bal", syntaxTree); + } } + diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/QueryParameterTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/QueryParameterTests.java index 39723a7af..0802b35be 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/QueryParameterTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/QueryParameterTests.java @@ -18,9 +18,13 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.cmd.CmdUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; @@ -45,8 +49,12 @@ public class QueryParameterTests { @Test(description = "01. Required query parameter has primitive data type") public void requiredQueryParameterPrimitive() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_01.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_01.bal", syntaxTree); } @@ -54,8 +62,12 @@ public void requiredQueryParameterPrimitive() throws IOException, BallerinaOpenA @Test(description = "02. Required query parameter has array data type") public void requiredQueryParameterPrimitiveArray() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_02.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_02.bal", syntaxTree); } @@ -66,8 +78,12 @@ public void requiredQueryParameterPrimitiveArray() throws IOException, Ballerina public void requiredQueryParameterPrimitiveNestedArray() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_03.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query.bal", syntaxTree); } @@ -77,8 +93,12 @@ public void requiredQueryParameterPrimitiveNestedArray() expectedExceptionsMessageRegExp = "Query parameters with no array item type can not be mapped to.*") public void requiredQueryParameterArrayHasNoItemType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_04.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query.bal", syntaxTree); } @@ -95,8 +115,12 @@ public void requiredQueryParameterArrayHasNoItemType() throws IOException, Balle @Test(description = "05. Nullable optional query parameter") public void nullableQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_05.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_05.bal", syntaxTree); } @@ -104,8 +128,12 @@ public void nullableQueryParameter() throws IOException, BallerinaOpenApiExcepti @Test(description = "06. Nullable query parameter with array") public void nullableQueryParameterWithArray() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_06.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_06.bal", syntaxTree); } @@ -116,8 +144,12 @@ public void nullableQueryParameterWithArray() throws IOException, BallerinaOpenA public void optionalQueryParameterPrimitiveNestedArray() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_07.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query.bal", syntaxTree); } @@ -127,8 +159,12 @@ public void optionalQueryParameterPrimitiveNestedArray() expectedExceptionsMessageRegExp = "Query parameters with no array item type can not be mapped to .*") public void optionalQueryParameterArrayHasNoItemType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_08.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query.bal", syntaxTree); } @@ -147,8 +183,12 @@ public void optionalQueryParameterArrayHasNoItemType() throws IOException, Balle public void defaultQueryParameter() throws IOException, BallerinaOpenApiException, FormatterException { Path definitionPath = RES_DIR.resolve("swagger/query/query_09.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_09.bal", syntaxTree); } @@ -159,8 +199,12 @@ public void defaultQueryParameter() " Ballerina resource query .*") public void defaultQueryParameterArrayHasNoItemType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_10.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query.bal", syntaxTree); } @@ -168,8 +212,12 @@ public void defaultQueryParameterArrayHasNoItemType() throws IOException, Baller @Test(description = "11. Required query parameter has nullable true") public void requiredNullableQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_11.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_11.bal", syntaxTree); } @@ -177,8 +225,12 @@ public void requiredNullableQueryParameter() throws IOException, BallerinaOpenAp @Test(description = "12. Required query parameter has map type") public void mapJsonQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_12.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_12.bal", syntaxTree); } @@ -186,8 +238,12 @@ public void mapJsonQueryParameter() throws IOException, BallerinaOpenApiExceptio @Test(description = "13. Default query parameter has string type") public void stringDefaultQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_13.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_13.bal", syntaxTree); } @@ -195,18 +251,118 @@ public void stringDefaultQueryParameter() throws IOException, BallerinaOpenApiEx @Test(description = "14. Fix the query parameter order") public void queryParameterOrder() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_14.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_14.bal", syntaxTree); } - @Test(description = "14.Optional query parameter") + @Test(description = "15. Optional query parameter") public void optionalQueryParameter() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/query/query_15.yaml"); - OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OpenAPI openAPI = CmdUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("query/query_15.bal", syntaxTree); } + + @Test(description = "16. Query parameter(s) having a referenced schema") + public void generateParamsWithRefSchema() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_ref_schema.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, false); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "parameters_with_object_ref_schema.bal", syntaxTree); + } + + @Test(description = "17. Query parameter(s) having a referenced schema of unsupported type", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "Type 'xml' is not a valid query parameter type in Ballerina. " + + "The supported types are string, int, float, boolean, decimal, array types of the aforementioned " + + "types and map.") + public void generateParamsWithInvalidRefSchema() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_invalid_ref_schema.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "18. Query parameter(s) having a referenced schema of array of unsupported type", + expectedExceptions = BallerinaOpenApiException.class, + expectedExceptionsMessageRegExp = "OpenAPI definition has errors: \n" + + "attribute components.schemas.Room.content is unexpected.*") + public void generateParamsWithInvalidArrayRefSchema() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameter_with_ref_array_invalid_schema.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + } + + @Test(description = "19. Query parameter(s) having a referenced schema type") + public void generateParamsWithObjectRefSchema() throws IOException, BallerinaOpenApiException, FormatterException { + Path definitionPath = RES_DIR.resolve("swagger/parameters_with_object_ref_schema.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "query/parameters_with_object_ref_schema.bal", syntaxTree); + } + + @Test(description = "20. Query parameter(s) having a referenced schema of array type") + public void generateParamsWithObjectArrayRefSchema() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/parameter_with_ref_array_object_schema.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "query/parameter_with_ref_array_object_schema.bal", syntaxTree); + } + + @Test(description = "21. Query parameter(s) having a object schema") + public void generateParamsWithObjectType() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/query/object_query.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, false); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "query/object_query.bal", syntaxTree); + //Check types + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "query/object_query_type.bal", syntaxTree); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/RequestBodyTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/RequestBodyTests.java index cf622d577..d79514f14 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/RequestBodyTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/RequestBodyTests.java @@ -19,12 +19,14 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; -import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; import java.io.IOException; @@ -43,13 +45,16 @@ public class RequestBodyTests { List list2 = new ArrayList<>(); Filter filter = new Filter(list1, list2); SyntaxTree syntaxTree; - public static final CodeGenerator CODE_GENERATOR = new CodeGenerator(); @Test(description = "Scenario 01 - Request Body has single content type(application/json)") public void generateJsonPayload() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/scenario01_rb.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("requestBody/scenario_01_rb.bal", syntaxTree); @@ -59,7 +64,11 @@ public void generateJsonPayload() throws IOException, BallerinaOpenApiException public void generateOtherPayload() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/scenario01_02_rb.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("requestBody/scenario_0102_rb.bal", syntaxTree); @@ -69,27 +78,39 @@ public void generateOtherPayload() throws IOException, BallerinaOpenApiException public void generateRBsameDataBindingPayload() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/scenario02_rb.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("requestBody/scenario_02_rb.bal", syntaxTree); } @Test(description = "Scenario 03 - Request Body has multiple content types with Different dataBind schema types.") - public void generateMultipleContent() throws IOException, BallerinaOpenApiException, FormatterException { - Path definitionPath = RES_DIR.resolve("swagger/requestBody/scenario03_rb.yaml"); + public void generateMultipleContent() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/requestBody/multiple_content.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("requestBody/scenario_03_rb.bal", syntaxTree); } @Test(description = "Scenario 04 - Request Body has record name with special characters.") - public void generateRecordName() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateRecordName() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/record_name_refactor.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "requestBody/refactor_record_name.bal", syntaxTree); @@ -99,7 +120,11 @@ public void generateRecordName() throws IOException, BallerinaOpenApiException, public void generateForMediaType() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/scenario04_rb.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "requestBody/scenario_04_rb.bal", syntaxTree); @@ -108,18 +133,33 @@ public void generateForMediaType() throws IOException, BallerinaOpenApiException @Test(description = "RequestBody has oneOf scenarios") public void oneOfScenarios() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/oneOf_request_body.yaml"); - BallerinaServiceGenerator ballerinaServiceGenerator = - new BallerinaServiceGenerator(CODE_GENERATOR.normalizeOpenAPI(definitionPath, false), filter); - syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(GeneratorUtils.normalizeOpenAPI(definitionPath, false)) + .withFilters(filter) + .build(); + BallerinaServiceGenerator serviceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = serviceGenerator.generateSyntaxTree(); + //Generate records according to schemas + List typeInclusionRecords = serviceGenerator.getTypeInclusionRecords(); + BallerinaTypesGenerator recordGenerator = new BallerinaTypesGenerator( + oasServiceMetadata.getOpenAPI(), oasServiceMetadata.isNullable(), typeInclusionRecords); + SyntaxTree typeSyntaxTree = recordGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "requestBody/oneof_requestBody.bal", syntaxTree); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/oneof_request_body_types.bal", typeSyntaxTree); + } @Test(description = "RequestBody has url encode media type scenarios") public void uRLEncode() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/url_form_encode.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "requestBody/url_encode.bal", syntaxTree); @@ -129,9 +169,76 @@ public void uRLEncode() throws IOException, BallerinaOpenApiException { public void referenceRequestBody() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/requestBody/reference_rb.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "requestBody/reference_rb.bal", syntaxTree); } + + @Test + public void testForRequestBodyHasMultipartFormDataPayload() + throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/requestBody/multipart_form_data.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/multipart_form_data.bal", syntaxTree); + } + + + @Test(description = "RequestBody has unhandled media type ex: application/zip") + public void testForUnhandledMediaType() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/requestBody/unhandled_media_type.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/unhandled_media_type.bal", syntaxTree); + } + + @Test(description = "RequestBody has anyOf type") + public void testForAnyOf() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/requestBody/any_of.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/any_of.bal", syntaxTree); + } + + @Test(description = "RequestBody has object type with additional property") + public void testForAdditionalProperty() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/requestBody/additional_property.yaml"); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, false); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + BallerinaTypesGenerator ballerinaTypesGenerator = new BallerinaTypesGenerator(openAPI, false, + ballerinaServiceGenerator.getTypeInclusionRecords()); + SyntaxTree typeSyntaxTree = ballerinaTypesGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/additional_property.bal", syntaxTree); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "requestBody/additional_prop_types.bal", typeSyntaxTree); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ReturnTypeTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ReturnTypeTests.java index 7f6df811a..8b35f8f78 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ReturnTypeTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ReturnTypeTests.java @@ -19,11 +19,12 @@ package io.ballerina.openapi.generators.service; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; import io.swagger.v3.oas.models.OpenAPI; -import org.ballerinalang.formatter.core.FormatterException; import org.testng.annotations.Test; import java.io.IOException; @@ -45,154 +46,222 @@ public class ReturnTypeTests { // Response scenarios @Test(description = "Scenario 01 - Response has single response without content type") - public void generateResponseScenario01() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario01() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_01_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_01_rs.bal", syntaxTree); } @Test(description = "Scenario 02 - Single response with content type") - public void generateResponseScenario02() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario02() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_02_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_02_rs.bal", syntaxTree); } @Test(description = "Scenario 03 - Single response with content type application/json") - public void generateResponseScenario03() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario03() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_03_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_03_rs.bal", syntaxTree); } @Test(description = "Scenario 04 - Response has multiple responses without content type") - public void generateResponseScenario04() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario04() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_04_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_04_rs.bal", syntaxTree); } @Test(description = "Scenario 05 - Error response with a schema") - public void generateResponseScenario05() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario05() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_05_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_05_rs.bal", syntaxTree); } @Test(description = "Scenario 06 - Error response with a schema with application/json") - public void generateResponseScenario06() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario06() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_06_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_06_rs.bal", syntaxTree); } @Test(description = "Scenario 07 - Single response has multiple content types") - public void generateResponseScenario07() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario07() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_07_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_07_rs.bal", syntaxTree); } @Test(description = "Scenario 08 - Single response has inline record for dataType") - public void generateResponseScenario08() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario08() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_08_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_08_rs.bal", syntaxTree); } @Test(description = "Scenario 09 - Single response has inline record for dataType with different status code") - public void generateResponseScenario09() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario09() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_09_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_09_rs.bal", syntaxTree); } @Test(description = "Scenario 10 - Response with a custom media type") - public void generateResponseScenario10() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario10() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_10_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_10_rs.bal", syntaxTree); } @Test(description = "Scenario 11 - Response has OneOf and AnyOf type 200 ok") - public void generateResponseScenario11() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario11() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_11_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_11_rs.bal", syntaxTree); } @Test(description = "Scenario 12 - Response has OneOf and AnyOf type for error status code") - public void generateResponseScenario12() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario12() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_12_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_12_rs.bal", syntaxTree); } @Test(description = "Scenario 13 - Single response has multiple content types with different error code") - public void generateResponseScenario13() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario13() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_13_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_13_rs.bal", syntaxTree); } @Test(description = "Scenario 14 - Multiple response with same mediaType") - public void generateResponseScenario14() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario14() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_14_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_14_rs.bal", syntaxTree); } @Test(description = "Scenario 15 - Response has array type data Binding") - public void generateResponseScenario15() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario15() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_15_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_15_rs.bal", syntaxTree); } @Test(description = "Scenario 16 - Response has array type data Binding with error code") - public void generateResponseScenario16() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario16() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_16_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_16_rs.bal", syntaxTree); } @Test(description = "Scenario 19 - Multiple response with different mediaType") - public void generateResponseScenario19() throws IOException, BallerinaOpenApiException, FormatterException { + public void generateResponseScenario19() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_19_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_19_rs.bal", syntaxTree); } @@ -201,7 +270,11 @@ public void generateResponseScenario19() throws IOException, BallerinaOpenApiExc public void generateResponseScenario20() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_20_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_20_rs.bal", syntaxTree); } @@ -210,37 +283,52 @@ public void generateResponseScenario20() throws IOException, BallerinaOpenApiExc public void generateResponseScenario21() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/scenario_21_rs.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/scenario_21_rs.bal", syntaxTree); } @Test(description = "Default response handling") - public void generateResponseDefault() throws IOException, BallerinaOpenApiException, - FormatterException { + public void generateResponseDefault() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/petstore_default.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/petstore_default.bal", syntaxTree); } @Test(description = "Path with special characters ") - public void testWithSpecialCharacters() throws IOException, BallerinaOpenApiException, FormatterException { + public void testWithSpecialCharacters() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/path_with_special_characters.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "response/path_with_special_characters.bal", syntaxTree); } @Test(description = "Response has different status code except 200") - public void testWithDifferentStatusCode() throws IOException, BallerinaOpenApiException, FormatterException { + public void testWithDifferentStatusCode() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/different_status_code.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "response/different_status_code.bal", syntaxTree); @@ -250,16 +338,24 @@ public void testWithDifferentStatusCode() throws IOException, BallerinaOpenApiEx public void testForNotSupportedStatusCode() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/real_apis/box.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("real_apis/box.bal", syntaxTree); } @Test(description = "Response and Request body have inline object schema") - public void testWithInlineObjectSchema() throws IOException, BallerinaOpenApiException, FormatterException { + public void testWithInlineObjectSchema() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/inline_record_type_request_response.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "inline_record.bal", syntaxTree); @@ -269,18 +365,109 @@ public void testWithInlineObjectSchema() throws IOException, BallerinaOpenApiExc public void toAllResponseCode() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/response_codes.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( "response/response_codes.bal", syntaxTree); } @Test(description = "Single response without content type.") - public void singleResponseWithOutContent() throws IOException, BallerinaOpenApiException, FormatterException { + public void singleResponseWithOutContent() throws IOException, BallerinaOpenApiException { Path definitionPath = RES_DIR.resolve("swagger/response/content_null.yaml"); OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); - BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(openAPI, filter); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/content_null.bal", syntaxTree); } + + @Test + public void testForUnsupportedReturnPayload() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/unsupportedPayloadType.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/unsupportedPayload.bal", + syntaxTree); + } + + @Test + public void testForResponseHasReference() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/reference_response.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "response/reference_response.bal", syntaxTree); + } + + @Test + public void testForAdditionalProReturnPayload() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/response_has_additional_properties.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "response/response_has_additional_properties.bal", syntaxTree); + } + + @Test(description = "Test for the POST method resource return generation. If 201 with schema type, then it " + + "generates only schema type without status code") + public void testForPostMethod() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/post_method.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/post_method.bal", syntaxTree); + } + + @Test(description = "Test for the resource function return generation when the response is empty") + public void testForEmptyResponse() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/empty_response.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree("response/empty_response.bal", syntaxTree); + } + + @Test(description = "Test for the resource function return generation when the response is empty") + public void testForMultilineReturnDescription() throws IOException, BallerinaOpenApiException { + Path definitionPath = RES_DIR.resolve("swagger/response/multiline_return_description.yaml"); + OpenAPI openAPI = GeneratorUtils.getOpenAPIFromOpenAPIV3Parser(definitionPath); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + CommonTestFunctions.compareGeneratedSyntaxTreewithExpectedSyntaxTree( + "response/multiline_return_description.bal", syntaxTree); + } } diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ServiceDiagnosticTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ServiceDiagnosticTests.java new file mode 100644 index 000000000..374524eb6 --- /dev/null +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/service/ServiceDiagnosticTests.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. + * + * 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.openapi.generators.service; + +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.service.BallerinaServiceGenerator; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.openapi.generators.common.TestUtils; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.SpecVersion; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.Assert; +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 java.util.ArrayList; +import java.util.List; + +import static io.ballerina.openapi.generators.common.TestUtils.getDiagnosticsForGenericService; +import static io.ballerina.openapi.generators.common.TestUtils.getDiagnosticsForService; +import static io.ballerina.openapi.generators.common.TestUtils.normalizeOpenAPI; + +/** + * Tests related to the check diagnostic issue in Ballerina service generation. + */ +public class ServiceDiagnosticTests { + private static final Path RESDIR = + Paths.get("src/test/resources/generators/diagnostic_files").toAbsolutePath(); + SyntaxTree syntaxTree; + List list1 = new ArrayList<>(); + List list2 = new ArrayList<>(); + Filter filter = new Filter(list1, list2); + + @Test(description = "Test for compilation errors in OpenAPI definition to ballerina service skeleton generation", + dataProvider = "singleFileProviderForDiagnosticCheck") + public void checkDiagnosticIssues(String yamlFile) throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .withNullable(false) + .withGenerateServiceType(false) + .withGenerateWithoutDataBinding(false) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + List diagnostics = getDiagnosticsForService(syntaxTree, openAPI, ballerinaServiceGenerator); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } + + @Test(description = "Test for compilation errors in OpenAPI definition to ballerina service skeleton generation", + dataProvider = "singleFileProviderForDiagnosticCheck") + public void checkDiagnosticIssuesInGenericServiceGen(String yamlFile) throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .withNullable(false) + .withGenerateServiceType(false) + .withGenerateWithoutDataBinding(true) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + List diagnostics = getDiagnosticsForGenericService(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } + + @Test(description = "Test for compilation errors in OpenAPI 3.1.0 definition to ballerina service " + + "skeleton generation", + dataProvider = "fileProviderForOpenAPI31DiagnosticCheck") + public void checkDiagnosticIssuesWith31OpenAPIs(String yamlFile) throws IOException, BallerinaOpenApiException, + FormatterException { + Path definitionPath = RESDIR.resolve(yamlFile); + OpenAPI openAPI = normalizeOpenAPI(definitionPath, true, SpecVersion.V31); + OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder() + .withOpenAPI(openAPI) + .withFilters(filter) + .withNullable(false) + .withGenerateServiceType(false) + .withGenerateWithoutDataBinding(false) + .build(); + BallerinaServiceGenerator ballerinaServiceGenerator = new BallerinaServiceGenerator(oasServiceMetadata); + syntaxTree = ballerinaServiceGenerator.generateSyntaxTree(); + List diagnostics = getDiagnosticsForService(syntaxTree, openAPI, ballerinaServiceGenerator); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + Assert.assertFalse(hasErrors); + } + + @DataProvider(name = "singleFileProviderForDiagnosticCheck") + public Object[][] singleFileProviderForDiagnosticCheck() { + return new Object[][] { + {"petstore_server_with_base_path.yaml"}, + {"petstore_get.yaml"}, + // TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1416 +// {"openapi_display_annotation.yaml"}, // not working, unknown type '200 + {"header_parameter.yaml"}, + {"petstore_post.yaml"}, + {"petstore_with_oneOf_response.yaml"}, + {"response_nested_array.yaml"}, + {"xml_payload.yaml"}, + {"xml_payload_with_ref.yaml"}, + {"duplicated_response.yaml"}, + {"complex_oneOf_schema.yaml"}, + {"request_body_ref.yaml"}, + {"vendor_specific_mime_types.yaml"}, + // TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1415 +// {"ballerinax_connector_tests/ably.yaml"}, + {"ballerinax_connector_tests/azure.iot.yaml"}, + // TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1440 +// {"ballerinax_connector_tests/beezup.yaml"}, + {"ballerinax_connector_tests/files.com.yaml"}, + {"ballerinax_connector_tests/openweathermap.yaml"}, + {"ballerinax_connector_tests/soundcloud.yaml"}, + {"ballerinax_connector_tests/stripe.yaml"}, + {"ballerinax_connector_tests/vimeo.yaml"}, +// {"ballerinax_connector_tests/ynab.yaml"}, // 209 status code is not supported in Ballerina + {"ballerinax_connector_tests/zoom.yaml"} + }; + } + + @DataProvider(name = "fileProviderForOpenAPI31DiagnosticCheck") + public Object[][] fileProviderForOpenAPI31DiagnosticCheck() { + return new Object[][]{ + {"petstore_server_with_base_path.yaml"}, + {"petstore_get.yaml"}, + {"openapi_display_annotation.yaml"}, + {"header_parameter.yaml"}, + {"petstore_post.yaml"}, + {"petstore_with_oneOf_response.yaml"}, + {"response_nested_array.yaml"}, + {"xml_payload.yaml"}, + {"xml_payload_with_ref.yaml"}, + {"duplicated_response.yaml"}, + {"complex_oneOf_schema.yaml"}, + {"request_body_ref.yaml"}, + {"vendor_specific_mime_types.yaml"}, +// {"ballerinax_connector_tests/ably.yaml"}, // HTTP status code '2XX' is not supported in Ballerina + {"ballerinax_connector_tests/azure.iot.yaml"}, + //TODO: Uncomment when fixed https://github.com/ballerina-platform/openapi-tools/issues/1440 +// {"ballerinax_connector_tests/beezup.yaml"}, + {"ballerinax_connector_tests/files.com.yaml"}, + {"ballerinax_connector_tests/openweathermap.yaml"}, + {"ballerinax_connector_tests/soundcloud.yaml"}, +// {"ballerinax_connector_tests/stripe.yaml"}, // not working due to anyOf schema in parameters + {"ballerinax_connector_tests/vimeo.yaml"}, +// {"ballerinax_connector_tests/ynab.yaml"}, // HTTP status code '209' is not supported in Ballerina. + {"ballerinax_connector_tests/zoom.yaml"}, + {"3.1.0_openapis/adyen_accountservice.yaml"}, +// {"3.1.0_openapis/codat_accounting.yaml"}, // openapi file has errors +// {"3.1.0_openapis/codat_bank_feeds.yaml"}, // openapi file has errors +// {"3.1.0_openapis/disclosure.yaml"}, // openapi file has errors + {"3.1.0_openapis/listennotes.yaml"}, + {"3.1.0_openapis/placekit.yaml"}, + {"3.1.0_openapis/urlbox.yaml"}, +// {"3.1.0_openapis/vercel.yaml"}, // uncomment when /openapi-tools/issues/1332 is fixed + {"3.1.0_openapis/webscraping.yaml"}, + {"3.1.0_openapis/wolframalpha.yaml"} + }; + } + + @AfterTest + public void cleanUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } +} diff --git a/openapi-cli/src/test/java/io/ballerina/openapi/generators/testcases/BallerinaTestGeneratorTests.java b/openapi-cli/src/test/java/io/ballerina/openapi/generators/testcases/BallerinaTestGeneratorTests.java index e4aa38a59..8df85286e 100644 --- a/openapi-cli/src/test/java/io/ballerina/openapi/generators/testcases/BallerinaTestGeneratorTests.java +++ b/openapi-cli/src/test/java/io/ballerina/openapi/generators/testcases/BallerinaTestGeneratorTests.java @@ -19,13 +19,16 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.openapi.cmd.CodeGenerator; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.client.BallerinaClientGenerator; -import io.ballerina.openapi.generators.client.BallerinaTestGenerator; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.cmd.BallerinaCodeGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.BallerinaTestGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.openapi.generators.common.TestUtils; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; import io.ballerina.tools.diagnostics.Diagnostic; import io.swagger.v3.oas.models.OpenAPI; import org.ballerinalang.formatter.core.Formatter; @@ -41,10 +44,11 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; -import static io.ballerina.openapi.generators.GeneratorConstants.OAS_PATH_SEPARATOR; -import static io.ballerina.openapi.generators.GeneratorConstants.TEST_DIR; +import static io.ballerina.openapi.cmd.CmdConstants.OAS_PATH_SEPARATOR; +import static io.ballerina.openapi.cmd.CmdConstants.TEST_DIR; /** * Test cases related to ballerina test skeleton generation. @@ -67,14 +71,23 @@ public void generateclientWithTestSkel(String yamlFile) throws IOException, Ball FormatterException, BallerinaOpenApiException, URISyntaxException { Files.createDirectories(Paths.get(PROJECT_DIR + OAS_PATH_SEPARATOR + TEST_DIR)); Path definitionPath = RES_DIR.resolve("sample_yamls/" + yamlFile); - CodeGenerator codeGenerator = new CodeGenerator(); + BallerinaCodeGenerator codeGenerator = new BallerinaCodeGenerator(); codeGenerator.setIncludeTestFiles(true); - OpenAPI openAPI = codeGenerator.normalizeOpenAPI(definitionPath, true); - BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(openAPI, filter, false, false); - BallerinaTypesGenerator schemaGenerator = new BallerinaTypesGenerator(openAPI); - schemaGenerator.setTypeDefinitionNodeList(ballerinaClientGenerator.getTypeDefinitionNodeList()); - BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(ballerinaClientGenerator); + OpenAPI openAPI = GeneratorUtils.normalizeOpenAPI(definitionPath, true); + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + OASClientConfig oasClientConfig = clientMetaDataBuilder + .withFilters(filter) + .withOpenAPI(openAPI) + .withResourceMode(false).build(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); SyntaxTree syntaxTreeClient = ballerinaClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefinitionNodes = new LinkedList<>(); + preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator. + getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList()); + BallerinaTypesGenerator schemaGenerator = new BallerinaTypesGenerator( + openAPI, false, preGeneratedTypeDefinitionNodes); + BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(ballerinaClientGenerator); SyntaxTree syntaxTreeTest = ballerinaTestGenerator.generateSyntaxTree(); SyntaxTree syntaxTreeSchema = schemaGenerator.generateSyntaxTree(); SyntaxTree utilSyntaxTree = ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); @@ -87,10 +100,10 @@ public void generateclientWithTestSkel(String yamlFile) throws IOException, Ball 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(clientPath, Formatter.format(clientSyntaxTree).toSourceCode()); + TestUtils.writeFile(utilPath, Formatter.format(utilSyntaxTree).toSourceCode()); + TestUtils.writeFile(schemaPath, Formatter.format(schemaSyntaxTree).toSourceCode()); + TestUtils.writeFile(testPath, Formatter.format(testSyntaxTree).toSourceCode()); TestUtils.writeFile(configPath, configContent); SemanticModel semanticModel = TestUtils.getSemanticModel(clientPath); return semanticModel.diagnostics(); @@ -117,7 +130,7 @@ public Object[] dataProvider() { "oauth2_implicit.yaml", "query_api_key.yaml", "no_auth.yaml", - "combination_of_apikey_and_http_oauth.yaml", +// "combination_of_apikey_and_http_oauth.yaml", "oauth2_password.yaml" }; } diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners.bal new file mode 100644 index 000000000..15bee4e5b --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners.bal @@ -0,0 +1,3 @@ +import ballerina/http; + +public listener http:Listener ep_with_host = new (443, config = {host: "http://petstore.openapi.io"}); diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_file.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_file.bal new file mode 100644 index 000000000..653088bf5 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_file.bal @@ -0,0 +1,9 @@ +import ballerina/http; + +public listener http:Listener ep_without_host = new (80); + +service /payloadV on ep_without_host, ep_with_host { + resource function get pets() returns string { + return "done"; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_module.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_module.bal new file mode 100644 index 000000000..9a5715aa3 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/listeners_in_separate_module.bal @@ -0,0 +1,7 @@ +import 'service.representations as rep; + +service /payloadV on rep:ep01, rep:ep02 { + resource function get pets() returns string { + return "done"; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/modules/representations/representations.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/modules/representations/representations.bal index 7584b5994..0f6988aa7 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/modules/representations/representations.bal +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/modules/representations/representations.bal @@ -147,3 +147,27 @@ public type PaymentConflict record {| *http:Conflict; 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} +]; + +public listener http:Listener ep01 = new (80); +public listener http:Listener ep02 = new (443, config = {host: "http://petstore.openapi.io"}); diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/readonly.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/readonly.bal new file mode 100644 index 000000000..a466fdf39 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/ballerina-project/service/readonly.bal @@ -0,0 +1,31 @@ +import ballerina/http; +import 'service.representations as ds; + +service /payloadV on new http:Listener(9090) { + + # A list of all `Lift`s + # + return - the lifts + resource function get lifts(string? status = ()) returns ds:LiftRecord[] { + ds:LiftRecord[] lifts; + if status !is () { + lifts = from var lift in ds:liftTable + where lift.status == status + select lift; + } else { + lifts = ds:liftTable.toArray(); + } + return lifts; + } + + # Returns a `Lift` by `id` (id: "panorama") + # + return - the lift + resource function get lift(string id) returns ds:LiftRecord? { + ds:LiftRecord[] lifts = from var lift in ds:liftTable + where lift.id == id + select lift; + if lifts.length() > 0 { + return lifts[0]; + } + return; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/catch_all_path_service.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/catch_all_path_service.bal new file mode 100644 index 000000000..e1d000390 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/catch_all_path_service.bal @@ -0,0 +1,28 @@ +import ballerina/http; + +public type Category record { + int id?; + string name?; +}; + +public type Tag record { + int id?; + string name?; +}; + +public type Pet record { + int id?; + string name; + Category category?; + string[] photoUrls; + Tag[] tags?; + string status?; +}; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /payloadV on ep0 { + resource function get '\*(int petId) returns Pet|error { + return {id: 1, name: "doggie", photoUrls: ["http://foo.bar.com/1", "http://foo.bar.com/2"]}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/bal_type_enum.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/bal_type_enum.bal new file mode 100644 index 000000000..899c61642 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/bal_type_enum.bal @@ -0,0 +1,14 @@ +import ballerina/http; + +enum Action { + DELIVERED, + RECEIVED, + PROCESS +} + +type Name Action; +service /payloadV on new http:Listener(9090) { + resource function post reservation(OrderType ird, @http:Payload Link link) returns Name { + return DELIVERED; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_header.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_header.bal new file mode 100644 index 000000000..1c94efb23 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_header.bal @@ -0,0 +1,59 @@ +import ballerina/http; + +listener http:Listener ep0 = new (9090); + +service /payloadV on ep0 { + resource function get users/meetings/[MeetingGroup group](@http:Header DateFormat 'x\-date\-required, @http:Header DateFormat? 'x\-date\-optional, @http:Header TimeZone[] 'x\-required\-arr, @http:Header TimeZone[]? 'x\-optional\-arr, @http:Header DateFormat[] x\-def\-arr = ["UTC"], @http:Header DateFormat x\-def\-header= "UTC" ) returns MeetingList|http:NotFound { + MeetingList m = { + meetings: [ + { + topic: "My topic" + } + ] + }; + return m; + } +} +public enum MeetingGroup { + ADMIN, + HR, + ENGINEERING +}; + +public enum Status { + AVAILABLE, + PENDING +} + +public enum DateFormat { + UTC, + LOCAL, + OFFSET, + EPOCH +} + +public enum TimeZone { + IST, + GMT, + UTC +} + +public enum Format { + JSON, + JSONP, + MSGPACK +} + +public enum RoomNo { + R3, + R5, + R6 +} + +public type MeetingList record { + Meeting[] meetings; +}; + +public type Meeting record { + string topic; +}; diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_query.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_query.bal new file mode 100644 index 000000000..d64189b5b --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/data_type/enum_query.bal @@ -0,0 +1,59 @@ +import ballerina/http; + +listener http:Listener ep0 = new (9090); + +service /payloadV on ep0 { + resource function get users/meetings/[MeetingGroup group](RoomNo required\-q\-ref, Status[] required\-q\-arr, Status[]? optional\-q\-arr, Format? format, "scheduled"|"live"|"upcoming" 'type = "live", RoomNo q\-default\-ref = "R5") returns MeetingList|http:NotFound { + MeetingList m = { + meetings: [ + { + topic: "My topic" + } + ] + }; + return m; + } +} +public enum MeetingGroup { + ADMIN, + HR, + ENGINEERING +}; + +public enum Status { + AVAILABLE, + PENDING +} + +public enum DateFormat { + UTC, + LOCAL, + OFFSET, + EPOCH +} + +public enum TimeZone { + IST, + GMT, + UTC +} + +public enum Format { + JSON, + JSONP, + MSGPACK +} + +public enum RoomNo { + R3, + R5, + R6 +} + +public type MeetingList record { + Meeting[] meetings; +}; + +public type Meeting record { + string topic; +}; diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/catch_all_path_service.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/catch_all_path_service.yaml new file mode 100644 index 000000000..b95ed3c33 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/catch_all_path_service.yaml @@ -0,0 +1,98 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: petstore3.swagger.io + port: + default: "443" +paths: + /*: + get: + operationId: get + parameters: + - name: petId + in: query + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + category: + $ref: '#/components/schemas/Category' + photoUrls: + type: array + items: + type: string + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + status: + type: string \ No newline at end of file diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/compiler_warning.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/compiler_warning.yaml index e78974dba..7a73a560c 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/compiler_warning.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/compiler_warning.yaml @@ -21,9 +21,32 @@ paths: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string -components: {} + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/bal_type_enum.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/bal_type_enum.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_header.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_header.yaml new file mode 100644 index 000000000..7fd159152 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_header.yaml @@ -0,0 +1,100 @@ +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: + /users/meetings/{group}: + get: + operationId: getUsersMeetingsGroup + parameters: + - name: group + in: path + required: true + schema: + $ref: '#/components/schemas/MeetingGroup' + - name: x-date-required + in: header + required: true + schema: + $ref: '#/components/schemas/DateFormat' + - name: x-date-optional + in: header + schema: + $ref: '#/components/schemas/DateFormat' + - name: x-required-arr + in: header + required: true + schema: + type: array + items: + $ref: '#/components/schemas/TimeZone' + - name: x-optional-arr + in: header + schema: + type: array + items: + $ref: '#/components/schemas/TimeZone' + - name: x-def-arr + in: header + schema: + type: array + items: + $ref: '#/components/schemas/DateFormat' + default: "[\"UTC\"]" + - name: x-def-header + in: header + schema: + $ref: '#/components/schemas/DateFormat' + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + "404": + description: NotFound +components: + schemas: + TimeZone: + type: string + enum: + - UTC + - GMT + - IST + Meeting: + required: + - topic + type: object + properties: + topic: + type: string + DateFormat: + type: string + enum: + - EPOCH + - OFFSET + - LOCAL + - UTC + MeetingList: + required: + - meetings + type: object + properties: + meetings: + type: array + items: + $ref: '#/components/schemas/Meeting' + MeetingGroup: + type: string + enum: + - ENGINEERING + - HR + - ADMIN diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_query.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_query.yaml new file mode 100644 index 000000000..98f28f00f --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/data_type/enum_query.yaml @@ -0,0 +1,107 @@ +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: + /users/meetings/{group}: + get: + operationId: getUsersMeetingsGroup + parameters: + - name: group + in: path + required: true + schema: + $ref: '#/components/schemas/MeetingGroup' + - name: required-q-ref + in: query + required: true + schema: + $ref: '#/components/schemas/RoomNo' + - name: required-q-arr + in: query + required: true + schema: + type: array + items: + $ref: '#/components/schemas/Status' + - name: optional-q-arr + in: query + schema: + type: array + nullable: true + items: + $ref: '#/components/schemas/Status' + - name: format + in: query + schema: + $ref: '#/components/schemas/Format' + - name: type + in: query + content: + application/json: + schema: + type: object + additionalProperties: true + default: live + - name: q-default-ref + in: query + required: true + schema: + $ref: '#/components/schemas/RoomNo' + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + "404": + description: NotFound +components: + schemas: + Status: + type: string + enum: + - PENDING + - AVAILABLE + RoomNo: + type: string + enum: + - R6 + - R5 + - R3 + Format: + type: string + enum: + - MSGPACK + - JSONP + - JSON + Meeting: + required: + - topic + type: object + properties: + topic: + type: string + MeetingList: + required: + - meetings + type: object + properties: + meetings: + type: array + items: + $ref: '#/components/schemas/Meeting' + MeetingGroup: + type: string + enum: + - ENGINEERING + - HR + - ADMIN diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/escape_identifier_02.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/escape_identifier_02.yaml index f2cdf6928..464e8e273 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/escape_identifier_02.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/escape_identifier_02.yaml @@ -29,11 +29,11 @@ paths: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /steps/{join}: get: summary: Header parameter @@ -59,11 +59,11 @@ paths: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /steps: post: operationId: postSteps @@ -73,18 +73,18 @@ paths: schema: $ref: '#/components/schemas/Offset' responses: - "200": - description: Ok + "201": + description: Created content: text/plain: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /พิมพ์ชื่อ: get: operationId: getพิมพ์ชื่อ @@ -110,6 +110,28 @@ paths: description: Accepted components: schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 Pet: required: - id diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/header_scenario04.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/header_scenario04.yaml index 5a51906f9..5d9090d16 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/header_scenario04.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/header_scenario04.yaml @@ -1,3 +1,14 @@ +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: /ping: get: @@ -11,9 +22,10 @@ paths: - name: x-request-client in: header schema: - type: string - nullable: true + type: array + items: + type: string responses: "200": description: Ok -components: {} + components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_file.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_file.yaml new file mode 100644 index 000000000..d9ab5a6aa --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_file.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + enum: + - http://localhost + - http://petstore.openapi.io + default: http://petstore.openapi.io + port: + enum: + - "80" + - "443" + default: "443" +paths: + /pets: + get: + operationId: getPets + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_module.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_module.yaml new file mode 100644 index 000000000..39d95ee9f --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/listeners_in_separate_module.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + enum: + - http://petstore.openapi.io + - http://localhost + default: http://localhost + port: + enum: + - "443" + - "80" + default: "80" +paths: + /pets: + get: + operationId: getPets + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_payload_complex.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_payload_complex.yaml new file mode 100644 index 000000000..76c31ea2f --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_payload_complex.yaml @@ -0,0 +1,65 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: petstore3.swagger.io + port: + default: "443" +paths: + /student1: + post: + operationId: postStudent1 + parameters: + - name: q + in: query + content: + application/json: + schema: + type: object + additionalProperties: true + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Student' + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + /student2: + post: + operationId: postStudent2 + parameters: + - name: q + in: query + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + type: string + responses: + "201": + description: Created + content: + application/json: + schema: + type: object +components: + schemas: + Student: + required: + - Name + type: object + properties: + Name: + type: string diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_query.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_query.yaml new file mode 100644 index 000000000..e39281db3 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/annotated_query.yaml @@ -0,0 +1,50 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: petstore3.swagger.io + port: + default: "443" +paths: + /student8: + post: + operationId: postStudent8 + parameters: + - name: student + in: query + content: + application/json: + schema: + type: object + additionalProperties: true + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + /student9: + post: + operationId: postStudent9 + parameters: + - name: students + in: query + content: + application/json: + schema: + type: object + additionalProperties: true + default: "{Name : John}" + responses: + "201": + description: Created + content: + application/json: + schema: + type: object +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/unannotated_payload.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/unannotated_payload.yaml new file mode 100644 index 000000000..441d34f6c --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/parameter_annotation/unannotated_payload.yaml @@ -0,0 +1,74 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: petstore3.swagger.io + port: + default: "443" +paths: + /student1: + post: + operationId: postStudent1 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Student' + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + /student2: + post: + operationId: postStudent2 + parameters: + - name: id + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Student' + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + /student3: + post: + operationId: postStudent3 + requestBody: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Student' + responses: + "201": + description: Created + content: + application/json: + schema: + type: object +components: + schemas: + Student: + required: + - Name + type: object + properties: + Name: + type: string diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/post_method.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/post_method.yaml new file mode 100644 index 000000000..4629bead1 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/post_method.yaml @@ -0,0 +1,83 @@ +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: + /pet: + post: + operationId: postPet + responses: + "201": + description: Created + content: + text/plain: + schema: + type: string + /pet2: + post: + operationId: postPet2 + responses: + "201": + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/User' + /cachingBackEnd: + post: + operationId: postCachingbackend + responses: + "201": + description: Created + headers: + Cache-Control: + schema: + type: string + default: "must-revalidate,public,max-age=3600" + ETag: + schema: + type: string + Last-Modified: + schema: + type: string + content: + text/plain: + schema: + type: string + /withMediaTypeOverrider: + post: + operationId: postWithmediatypeoverrider + responses: + "201": + description: Created + content: + application/json: + schema: + type: string + /pet3: + post: + operationId: postPet3 + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: + schemas: + User: + type: object + properties: + name: + type: string + id: + type: integer + format: int64 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/readonly.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/readonly.yaml new file mode 100644 index 000000000..2f6b7fd4b --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/readonly.yaml @@ -0,0 +1,78 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /lifts: + get: + summary: A list of all `Lift`s + operationId: getLifts + parameters: + - name: status + in: query + schema: + type: string + nullable: true + responses: + "200": + description: Ok + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LiftRecord' + /lift: + get: + summary: "Returns a `Lift` by `id` (id: \"panorama\")" + operationId: getLift + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/LiftRecord' +components: + schemas: + LiftRecord: + required: + - capacity + - elevationgain + - id + - name + - night + - status + type: object + properties: + id: + type: string + name: + type: string + status: + type: string + enum: + - HOLD + - CLOSED + - OPEN + capacity: + type: integer + format: int64 + night: + type: boolean + elevationgain: + type: integer + format: int64 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record.yaml index 5ab55be01..6318aa20e 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record.yaml @@ -14,8 +14,8 @@ paths: post: operationId: postPet responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -26,8 +26,8 @@ paths: post: operationId: postPet02 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -38,8 +38,8 @@ paths: post: operationId: postPet03 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -50,8 +50,8 @@ paths: post: operationId: postPet04 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -62,8 +62,8 @@ paths: post: operationId: postPet05 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -74,8 +74,8 @@ paths: post: operationId: postPet06 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -86,14 +86,26 @@ paths: post: operationId: postPet07 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: $ref: '#/components/schemas/ResponseError07' "202": description: Accepted + /items: + get: + operationId: getItems + responses: + "200": + description: Ok + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AidPackage' components: schemas: ResponseError: @@ -190,3 +202,24 @@ components: nullable: true items: $ref: '#/components/schemas/ResponseError07' + AidPackageItem: + required: + - totalAmount + type: object + properties: + totalAmount: + type: number + format: double + aidPackage: + $ref: '#/components/schemas/AidPackage' + AidPackage: + required: + - status + type: object + properties: + status: + type: string + aidPackageItems: + type: array + items: + $ref: '#/components/schemas/AidPackageItem' diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record_with_typeInclusion.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record_with_typeInclusion.yaml new file mode 100644 index 000000000..05316ffd1 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/cyclic_record_with_typeInclusion.yaml @@ -0,0 +1,75 @@ +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: + /fhir/r4/Patient/{id}: + get: + operationId: getFhirR4PatientId + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/fhir+json: + schema: + $ref: '#/components/schemas/Patient' + application/fhir+xml: + schema: + $ref: '#/components/schemas/Patient' +components: + schemas: + Identifier: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + value: + type: string + assigner: + $ref: '#/components/schemas/Reference' + id: + type: string + element: + type: integer + format: int64 + Reference: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + reference: + type: string + type: + type: string + identifier: + $ref: '#/components/schemas/Identifier' + display: + type: string + Element: + type: object + properties: + id: + type: string + element: + type: integer + format: int64 + Patient: + type: object + properties: + id: + type: string + ref: + $ref: '#/components/schemas/Reference' \ No newline at end of file diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/typeref_records_with_interdependency.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/typeref_records_with_interdependency.yaml new file mode 100644 index 000000000..863c90162 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/typeref_records_with_interdependency.yaml @@ -0,0 +1,95 @@ +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: + /fhir/r4/Patient/{id}: + get: + operationId: getFhirR4PatientId + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/fhir+json: + schema: + $ref: '#/components/schemas/Patient' + application/fhir+xml: + schema: + $ref: '#/components/schemas/Patient' +components: + schemas: + Extension: + $ref: '#/components/schemas/ExtensionExtension' + Identifier: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + value: + type: string + assigner: + $ref: '#/components/schemas/Reference' + id: + type: string + element: + type: integer + format: int64 + Reference: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + reference: + type: string + type: + type: string + identifier: + $ref: '#/components/schemas/Identifier' + display: + type: string + id: + type: string + element: + type: integer + format: int64 + Element: + type: object + properties: + id: + type: string + element: + type: integer + format: int64 + ExtensionExtension: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + extension: + type: array + items: + $ref: '#/components/schemas/Extension' + Patient: + type: object + properties: + ext: + type: array + items: + $ref: '#/components/schemas/Extension' + id: + type: string + ref: + $ref: '#/components/schemas/Reference' diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_records_with_interdependency.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_records_with_interdependency.yaml new file mode 100644 index 000000000..41699a1ff --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_records_with_interdependency.yaml @@ -0,0 +1,165 @@ +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: + /fhir/r4/Patient/{id}: + get: + operationId: getFhirR4PatientId + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/fhir+json: + schema: + $ref: '#/components/schemas/Patient' + application/fhir+xml: + schema: + $ref: '#/components/schemas/Patient' +components: + schemas: + Extension: + oneOf: + - $ref: '#/components/schemas/ExtensionExtension' + - $ref: '#/components/schemas/StringExtension' + - $ref: '#/components/schemas/CodingExtension' + - $ref: '#/components/schemas/CodeExtension' + - $ref: '#/components/schemas/IntegerExtension' + CodeExtension: + required: + - url + - valueCode + type: object + properties: + url: + $ref: '#/components/schemas/uri' + valueCode: + type: string + Identifier: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + value: + type: string + assigner: + $ref: '#/components/schemas/Reference' + id: + type: string + element: + type: integer + format: int64 + Coding: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + id: + type: string + extension: + type: array + items: + $ref: '#/components/schemas/Extension' + system: + $ref: '#/components/schemas/uri' + version: + type: string + display: + type: string + userSelected: + type: boolean + element: + type: integer + format: int64 + CodingExtension: + required: + - url + - valueCoding + type: object + properties: + url: + $ref: '#/components/schemas/uri' + valueCoding: + $ref: '#/components/schemas/Coding' + Reference: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + reference: + type: string + type: + type: string + identifier: + $ref: '#/components/schemas/Identifier' + display: + type: string + id: + type: string + element: + type: integer + format: int64 + Element: + type: object + properties: + id: + type: string + element: + type: integer + format: int64 + StringExtension: + required: + - url + - valueString + type: object + properties: + url: + $ref: '#/components/schemas/uri' + valueString: + type: string + ExtensionExtension: + allOf: + - $ref: '#/components/schemas/Element' + - type: object + properties: + extension: + type: array + items: + $ref: '#/components/schemas/Extension' + IntegerExtension: + required: + - url + - valueInteger + type: object + properties: + url: + $ref: '#/components/schemas/uri' + valueInteger: + type: integer + format: int64 + Patient: + type: object + properties: + ext: + type: array + items: + $ref: '#/components/schemas/Extension' + id: + type: string + ref: + $ref: '#/components/schemas/Reference' + uri: + type: string diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_with_nullable.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_with_nullable.yaml index 966cf48a6..9394d8c83 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_with_nullable.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/union_with_nullable.yaml @@ -30,6 +30,7 @@ components: rel: type: string pet: + nullable: true oneOf: - $ref: '#/components/schemas/Dog' - $ref: '#/components/schemas/Cat' diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/with_read_only_keyword.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/with_read_only_keyword.yaml index 3d000d839..8bcd2f744 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/with_read_only_keyword.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/record/with_read_only_keyword.yaml @@ -30,8 +30,8 @@ paths: schema: $ref: '#/components/schemas/Album' responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/rb_scenario09.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/rb_scenario09.yaml index d296316bd..fdcfd5b5c 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/rb_scenario09.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/rb_scenario09.yaml @@ -7,7 +7,7 @@ paths: application/octet-stream: schema: type: string - format: uuid + format: byte responses: "200": description: Ok diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/service_config_with_cors.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/service_config_with_cors.yaml new file mode 100644 index 000000000..e2abbd431 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/request_body/service_config_with_cors.yaml @@ -0,0 +1,59 @@ +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: + /greeting: + post: + summary: A resource for generating greetings + operationId: postGreeting + requestBody: + description: the input string name + content: + text/plain: + schema: + type: string + responses: + "201": + description: Created + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/byte.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/byte.yaml new file mode 100644 index 000000000..349f136c5 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/byte.yaml @@ -0,0 +1,59 @@ +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: + /challenges/{challenged}: + get: + operationId: getChallengesChallenged + parameters: + - name: challenged + in: path + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/octet-stream: + schema: + type: string + format: byte + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 \ No newline at end of file diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/cache_config_06.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/cache_config_06.yaml index 31a607e5d..d8751ee2b 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/cache_config_06.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/cache_config_06.yaml @@ -1,3 +1,14 @@ +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: /cachingBackEnd01: get: @@ -21,11 +32,11 @@ paths: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /cachingBackEnd02: get: operationId: getCachingbackend02 @@ -48,9 +59,32 @@ paths: schema: type: string "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string -components: {} + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/deprecated_status_code.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/deprecated_status_code.yaml new file mode 100644 index 000000000..6044e337d --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/deprecated_status_code.yaml @@ -0,0 +1,19 @@ +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: + /pet: + post: + operationId: postPet + responses: + "511": + description: NetworkAuthorizationRequired +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/no_body_field.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/no_body_field.yaml index 45e059430..f55b6f3fc 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/no_body_field.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/no_body_field.yaml @@ -17,9 +17,32 @@ paths: "204": description: NoContent "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string -components: {} + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/readonly.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/readonly.yaml new file mode 100644 index 000000000..63dafc3da --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/readonly.yaml @@ -0,0 +1,235 @@ +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: + /res1: + get: + operationId: getRes1 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyPet' + /res2: + get: + operationId: getRes2 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/ReadOnlyStr' + /res3: + get: + operationId: getRes3 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/ReadOnlyStrNil' + /res4: + get: + operationId: getRes4 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/ReadOnlyStrArray' + /res5: + get: + operationId: getRes5 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyMapJson' + /res6: + get: + operationId: getRes6 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyJson' + /res7: + get: + operationId: getRes7 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/xml: + schema: + $ref: '#/components/schemas/ReadOnlyXML' + /res8: + get: + operationId: getRes8 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "500": + description: Internal server error + content: + text/plain: + schema: + type: string + /res9: + get: + operationId: getRes9 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyPrimitiveUnion' + /res10: + get: + operationId: getRes10 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyBracedUnion' + /res11: + get: + operationId: getRes11 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReadOnlyRec' +components: + schemas: + ReadOnlyPet: + $ref: '#/components/schemas/Pet' + ReadOnlyRec: + required: + - id + - name + type: object + properties: + id: + type: string + name: + type: string + ReadOnlyStr: + type: string + ReadOnlyPrimitiveUnion: + oneOf: + - type: string + - type: integer + format: int64 + ReadOnlyMapJson: + type: object + additionalProperties: true + ReadOnlyJson: + type: object + ReadOnlyStrArray: + type: array + items: + type: string + ReadOnlyStrNil: + type: string + nullable: true + ReadOnlyBracedUnion: + oneOf: + - type: string + - type: integer + format: int64 + Pet: + required: + - name + type: object + properties: + name: + type: string + ReadOnlyXML: + type: object diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/response_code.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/response_code.yaml index 07c756f2a..7726e928c 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/response_code.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/response_code.yaml @@ -18,6 +18,10 @@ paths: description: Continue "101": description: SwitchingProtocols + "102": + description: Processing + "103": + description: EarlyHints "200": description: Ok "201": @@ -30,6 +34,12 @@ paths: description: NoContent "206": description: PartialContent + "207": + description: MultiStatus + "208": + description: AlreadyReported + "226": + description: IMUsed "300": description: MultipleChoices "301": @@ -80,12 +90,26 @@ paths: description: RangeNotSatisfiable "417": description: ExpectationFailed + "421": + description: MisdirectedRequest + "422": + description: UnprocessableEntity + "423": + description: Locked + "424": + description: FailedDependency + "425": + description: TooEarly "426": description: UpgradeRequired + "428": + description: PreconditionRequired "429": description: TooManyRequests "431": description: RequestHeaderFieldsTooLarge + "451": + description: UnavailableDueToLegalReasons "500": description: InternalServerError "501": @@ -96,4 +120,14 @@ paths: description: ServiceUnavailable "505": description: HttpVersionNotSupported + "506": + description: VariantAlsoNegotiates + "507": + description: InsufficientStorage + "508": + description: LoopDetected + "510": + description: NotExtended + "511": + description: NetworkAuthenticationRequired components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario09.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario09.yaml index 5a06b06e2..85d69033c 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario09.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario09.yaml @@ -36,8 +36,8 @@ paths: post: operationId: postHi responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -60,11 +60,11 @@ paths: format: int64 responses: "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /v1: post: operationId: postV1 @@ -78,6 +78,28 @@ paths: description: NotFound components: schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 Pet: required: - id diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario10.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario10.yaml index 3cf8948dc..e536098c1 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario10.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario10.yaml @@ -14,8 +14,8 @@ paths: post: operationId: postHi01 responses: - "200": - description: Ok + "201": + description: Created content: application/json: schema: @@ -26,8 +26,8 @@ paths: post: operationId: postHi responses: - "200": - description: Ok + "201": + description: Created content: text/plain: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario11.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario11.yaml index 891919ee3..a2e5dfd46 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario11.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario11.yaml @@ -14,8 +14,8 @@ paths: post: operationId: postHi responses: - "200": - description: Ok + "201": + description: Created content: text/plain: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario17.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario17.yaml index 402bcd245..c15c209f2 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario17.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario17.yaml @@ -19,8 +19,8 @@ paths: schema: $ref: '#/components/schemas/Pet' responses: - "200": - description: Ok + "201": + description: Created content: application/vnd.wso2.sales+json: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario18.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario18.yaml index 12332e2b4..de2720ed8 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario18.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario18.yaml @@ -28,8 +28,8 @@ paths: schema: $ref: '#/components/schemas/Pet' responses: - "200": - description: Ok + "201": + description: Created content: text/vnd.wso2.sales+plain: schema: @@ -48,8 +48,8 @@ paths: post: operationId: postHi responses: - "200": - description: Ok + "201": + description: Created content: text/vnd.wso2.sales+plain: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario20.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario20.yaml index 6934b9628..6df8c5ba0 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario20.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/rs_scenario20.yaml @@ -1,3 +1,14 @@ +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: /pet: get: @@ -10,11 +21,11 @@ paths: schema: description: Any type of entity body "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string + $ref: '#/components/schemas/ErrorPayload' /pets: get: operationId: getPets @@ -25,4 +36,27 @@ paths: application/json: schema: type: object -components: {} +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/same_status_code.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/same_status_code.yaml new file mode 100644 index 000000000..6bba3a590 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/same_status_code.yaml @@ -0,0 +1,86 @@ +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: + /testPath: + get: + operationId: getTestpath + responses: + "200": + description: Ok + content: + application/json: + schema: + oneOf: + - type: boolean + - type: integer + format: int64 + - $ref: '#/components/schemas/Pet' + - $ref: '#/components/schemas/Cat' + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 + Cat: + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Pet: + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors.yaml new file mode 100644 index 000000000..b6f039661 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors.yaml @@ -0,0 +1,60 @@ +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: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_with_slash.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_with_slash.yaml new file mode 100644 index 000000000..7576561a0 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_with_slash.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.1 +info: + title: Service Config With Cors With Slash Openapi Yaml + version: 0.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_without_base_path.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_without_base_path.yaml new file mode 100644 index 000000000..0d90160c2 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_config_with_cors_without_base_path.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.1 +info: + title: Service Config With Cors Without Base Path Openapi Yaml + version: 0.0.0 +servers: + - url: "{server}:{port}" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_error_and_internal_server_error.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_error_and_internal_server_error.yaml new file mode 100644 index 000000000..cbce3c275 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_error_and_internal_server_error.yaml @@ -0,0 +1,60 @@ +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: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: InternalServerError + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_same_status_code.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_same_status_code.yaml new file mode 100644 index 000000000..42e3a39ec --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/service_with_same_status_code.yaml @@ -0,0 +1,40 @@ +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: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + post: + operationId: postGreeting + responses: + "400": + description: BadRequest + content: + text/plain: + schema: + type: string +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/simple_name_ref.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/simple_name_ref.yaml new file mode 100644 index 000000000..0a5ede177 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response/simple_name_ref.yaml @@ -0,0 +1,337 @@ +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: + /lift01: + get: + operationId: getLift01 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/ReturnValueStr' + /lift02: + get: + operationId: getLift02 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueIntNil' + /lift03: + get: + operationId: getLift03 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueIntArray' + /lift05: + get: + operationId: getLift05 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueMapJson' + /lift06: + get: + operationId: getLift06 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueJson' + /lift07: + get: + operationId: getLift07 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueMapRec' + /lift08: + get: + operationId: getLift08 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueMapString' + /lift09: + get: + operationId: getLift09 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/xml: + schema: + $ref: '#/components/schemas/ReturnValueXML' + /lift10: + get: + operationId: getLift10 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "500": + description: Internal server error + content: + text/plain: + schema: + type: string + /lift11: + get: + operationId: getLift11 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValuePrimitiveUnion' + /lift12: + get: + operationId: getLift12 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ReturnValueRecUnion' + /res13: + get: + operationId: getRes13 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "400": + description: BadRequest + /res14: + get: + operationId: getRes14 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "400": + description: BadRequest + "200": + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResUnion' + /res16: + get: + operationId: getRes16 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/StrNil' + /res17: + get: + operationId: getRes17 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: '#/components/schemas/StrArray' + /res19: + get: + operationId: getRes19 + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + application/octet-stream: + schema: + $ref: '#/components/schemas/ByteArr' +components: + schemas: + ReturnValueJson: + type: object + ReturnValueIntNil: + type: integer + format: int64 + nullable: true + ReturnValueRecUnion: + oneOf: + - $ref: '#/components/schemas/Pet' + - $ref: '#/components/schemas/Dog' + ReturnValueIntArray: + type: array + items: + type: integer + format: int64 + StrArray: + type: array + items: + type: string + ReturnValueMapString: + type: object + additionalProperties: + type: string + ReturnValuePrimitiveUnion: + oneOf: + - type: number + format: float + - type: integer + format: int64 + ReturnValueMapJson: + type: object + additionalProperties: true + ReturnValueMapRec: + type: object + additionalProperties: + $ref: '#/components/schemas/Pet' + ReturnValueStr: + type: string + StrNil: + type: string + nullable: true + Dog: + required: + - breed + - isBark + type: object + properties: + breed: + type: string + isBark: + type: boolean + Pet: + required: + - name + type: object + properties: + name: + type: string + ErrorResUnion: + oneOf: + - type: number + format: float + - type: integer + format: int64 + ByteArr: + type: array + items: {} + ReturnValueXML: + type: object diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response02.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response02.yaml index c3e5f2e83..02e2f40ab 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response02.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/response02.yaml @@ -14,8 +14,8 @@ paths: post: operationId: postUser responses: - "200": - description: Ok + "201": + description: Created content: text/plain: schema: diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/status_code/not_acceptable.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/status_code/not_acceptable.yaml index 599495761..ccf554b4b 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/status_code/not_acceptable.yaml +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/status_code/not_acceptable.yaml @@ -17,9 +17,32 @@ paths: "406": description: NotAcceptable "500": - description: Found unexpected output + description: Internal server error content: - text/plain: + application/json: schema: - type: string -components: {} + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_file.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_file.yaml new file mode 100644 index 000000000..b71bae1b1 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_file.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://petstore.openapi.io + enum: + - http://localhost + - http://petstore.openapi.io + port: + default: "443" + enum: + - "80" + - "443" +paths: + /pets: + get: + operationId: getPets + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_module.yaml b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_module.yaml new file mode 100644 index 000000000..a590f0a01 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/expected_gen/windows_listeners_in_separate_module.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + enum: + - http://petstore.openapi.io + - http://localhost + port: + default: "80" + enum: + - "443" + - "80" +paths: + /pets: + get: + operationId: getPets + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: {} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/graphql_service.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/graphql_service.bal new file mode 100644 index 000000000..c0d9f4346 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/graphql_service.bal @@ -0,0 +1,7 @@ +import ballerina/graphql; + +service graphql:Service /query on new graphql:Listener(8080) { + resource function get name() returns string { + return "Jack"; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_payload_complex.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_payload_complex.bal new file mode 100644 index 000000000..af81e2fb5 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_payload_complex.bal @@ -0,0 +1,17 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +type Student record { + string Name; +}; + +service /payloadV on ep0 { + resource function post student1(@http:Payload Student student, map q) returns json { + return {Name: student.Name}; + } + + resource function post student2(@http:Payload string p, string q) returns json { + return {Name: p}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_query.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_query.bal new file mode 100644 index 000000000..abd65147c --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/annotated_query.bal @@ -0,0 +1,18 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +type Student record { + string Name; +}; + +service /payloadV on ep0 { + + resource function post student8(@http:Query map student) returns json { + return {Name: "john"}; + } + + resource function post student9(@http:Query map students = {"Name" : "John"}) returns json { + return {Name: "john"}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/invalid_payload.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/invalid_payload.bal new file mode 100644 index 000000000..b974dc757 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/invalid_payload.bal @@ -0,0 +1,14 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +type Student record { + string Name; +}; + +service /payloadV on ep0 { + resource function post student12(Student[] students, map q) returns json { + string name = students[0].Name; + return {Name: name}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/unannotated_payload.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/unannotated_payload.bal new file mode 100644 index 000000000..7c304b5ef --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/parameter_annotation/unannotated_payload.bal @@ -0,0 +1,25 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +type Student record { + string Name; +}; + +service /payloadV on ep0 { + + resource function post student1(Student student) returns json { + string name = student.Name; + return {Name: name}; + } + + resource function post student2(Student student, string id) returns json { + string name = student.Name; + return {Name: name, id: id}; + } + + resource function post student3(Student[] students) returns json { + string name = students[0].Name; + return {Name: name}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/post_method.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/post_method.bal new file mode 100644 index 000000000..75bc417f1 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/post_method.bal @@ -0,0 +1,45 @@ +import ballerina/http; + +public type User record { + string name?; + int id?; +}; + +public type OkString record {| + *http:Ok; + string body; +|}; + +service /payloadV on new http:Listener(9090) { + + //POST method is with default value + resource function post pet() returns string { + return "post"; + } + + resource function post pet2() returns User { + User u = { + name: "lna", + id: 94 + }; + return u; + } + + //With cache header details + resource function post cachingBackEnd() returns @http:Cache string { + return "Hello, World!!"; + } + + //With payload annotation for overriding content type + resource function post withMediaTypeOverrider() returns @http:Payload {mediaType: "application/json"} string { + return "Hello, World!!"; + } + + //With different status code record + resource function post pet3() returns OkString { + OkString u = { + body: "lna" + }; + return u; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record.bal index 306508575..1eeea967e 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record.bal +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record.bal @@ -35,6 +35,16 @@ type ResponseError07 record {| ResponseError07[]? resError; |}; +type AidPackage record {| + string status; + AidPackageItem[] aidPackageItems?; +|}; + +type AidPackageItem record {| + decimal totalAmount =0; + AidPackage aidPackage?; +|}; + listener http:Listener ep0 = new (443, config = {host: "petstore.swagger.io"}); service /payloadV on ep0 { @@ -66,4 +76,8 @@ service /payloadV on ep0 { http:Accepted accept = {body: ()}; return accept; } + resource function get items() returns AidPackage[] { + AidPackage aidPackage = {status:"Test"}; + return [aidPackage]; + } } diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record_with_typeInclusion.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record_with_typeInclusion.bal new file mode 100644 index 000000000..903c1bae3 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/record/cyclic_record_with_typeInclusion.bal @@ -0,0 +1,40 @@ +import ballerina/http; + +type Patient record {| + string id?; + Reference ref?; +|}; + +public type Reference record {| + *Element; + string reference?; + string 'type?; + Identifier identifier?; + string display?; +|}; + +public type Identifier record {| + *Element; + string value?; + Reference assigner?; +|}; + +public type Element record {| + string id?; + int element?; +|}; + + +service /payloadV on new http:Listener(9090) { + + // Read the current state of the resource represented by the given id. + isolated resource function get fhir/r4/Patient/[string id]() + returns @http:Payload {mediaType: ["application/fhir+json", "application/fhir+xml"]} + Patient { + Patient patient = { + id: id + }; + + return patient; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/record/typeref_records_with_interdependency.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/record/typeref_records_with_interdependency.bal new file mode 100644 index 000000000..b15613281 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/record/typeref_records_with_interdependency.bal @@ -0,0 +1,49 @@ +import ballerina/http; + + +type Patient record {| + Extension[] ext?; + string id?; + Reference ref?; +|}; + +public type Extension ExtensionExtension; + +public type ExtensionExtension record {| + *Element; + Extension[] extension?; +|}; + +public type Reference record {| + *Element; + string reference?; + string 'type?; + Identifier identifier?; + string display?; +|}; + +public type Identifier record {| + *Element; + string value?; + Reference assigner?; +|}; + +public type Element record {| + string id?; + int element?; +|}; + + +service /payloadV on new http:Listener(9090) { + + // Read the current state of the resource represented by the given id. + isolated resource function get fhir/r4/Patient/[string id]() + returns @http:Payload {mediaType: ["application/fhir+json", "application/fhir+xml"]} + Patient { + Patient patient = { + id: id + }; + + return patient; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/record/union_records_with_interdependency.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/record/union_records_with_interdependency.bal new file mode 100644 index 000000000..7724d251d --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/record/union_records_with_interdependency.bal @@ -0,0 +1,82 @@ +import ballerina/http; + + +type Patient record {| + Extension[] ext?; + string id?; + Reference ref?; +|}; + +public type Extension ExtensionExtension|StringExtension|CodingExtension|CodeExtension|IntegerExtension; + +public type ExtensionExtension record {| + *Element; + Extension[] extension?; +|}; + +public type StringExtension record {| + uri url; + string valueString; +|}; + +public type uri string; +public type CodingExtension record {| + uri url; + Coding valueCoding; +|}; + +public type Coding record {| + *Element; + + string id?; + Extension[] extension?; + uri system?; + string 'version?; + string display?; + boolean userSelected?; +|}; + +public type CodeExtension record {| + uri url; + string valueCode; +|}; + +public type IntegerExtension record {| + uri url; + int valueInteger; +|}; + + +public type Reference record {| + *Element; + string reference?; + string 'type?; + Identifier identifier?; + string display?; +|}; + +public type Identifier record {| + *Element; + string value?; + Reference assigner?; +|}; + +public type Element record {| + string id?; + int element?; +|}; + + +service /payloadV on new http:Listener(9090) { + + // Read the current state of the resource represented by the given id. + isolated resource function get fhir/r4/Patient/[string id]() + returns @http:Payload {mediaType: ["application/fhir+json", "application/fhir+xml"]} + Patient { + Patient patient = { + id: id + }; + + return patient; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/request_body/service_config_with_cors.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/request_body/service_config_with_cors.bal new file mode 100644 index 000000000..c9a3781d9 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/request_body/service_config_with_cors.bal @@ -0,0 +1,17 @@ +import ballerina/http; + +@http:ServiceConfig { + cors: { + allowOrigins: ["*"] + } +} + +service /payloadV on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function post greeting(@http:Payload string name) returns string|error { + return "Hello, "; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/byte.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/byte.bal new file mode 100644 index 000000000..8f402509d --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/byte.bal @@ -0,0 +1,15 @@ +import ballerina/http; + +public type ReturnValueXML xml; + +public type ReturnValueCustomRec record {| + *http:BadGateway; + ReturnValueXML body; +|}; + +service /payloadV on new http:Listener(9090) { + + resource function get challenges/[string challenged]() returns byte[]|error { + return error(""); + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/deprecated_status_code.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/deprecated_status_code.bal new file mode 100644 index 000000000..17e8f3749 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/deprecated_status_code.bal @@ -0,0 +1,7 @@ +import ballerina/http; + +service /payloadV on new http:Listener(9090) { + resource function post pet() returns http:NetworkAuthorizationRequired { + return {}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/readonly.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/readonly.bal new file mode 100644 index 000000000..690f1fcc3 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/readonly.bal @@ -0,0 +1,89 @@ +import ballerina/http; + +type Pet record { + string name; +}; + +public type ReadOnlyStr readonly & string; + +public type ReadOnlyPet readonly & Pet; + +public type ReadOnlyStrNil readonly & string?; + +public type ReadOnlyStrArray readonly & string[]; + +public type ReadOnlyMapJson readonly & map; + +public type ReadOnlyJson readonly & json; + +public type ReadOnlyXML readonly & xml; + +public type ReadOnlyError readonly & error; + +public type ReadOnlyPrimitiveUnion readonly & string|int; + +public type ReadOnlyBracedUnion readonly & (string|int); + +public type ReadOnlyRec readonly & record {| + readonly string id; + string name; +|}; + +service /payloadV on new http:Listener(9090) { + + resource function get res1(string id) returns ReadOnlyPet { + return { + name: "Kitty" + }; + } + + resource function get res2(string id) returns ReadOnlyStr { + return "Value"; + } + + resource function get res3(string id) returns ReadOnlyStrNil { + return (); + } + + resource function get res4(string id) returns ReadOnlyStrArray { + ReadOnlyStrArray values = ["val1", "val2"]; + return values; + } + + + resource function get res5(string id) returns ReadOnlyMapJson { + return {"map": {}}; + } + + resource function get res6(string id) returns ReadOnlyJson { + return { + "name": "test-user" + }; + } + + resource function get res7(string id) returns ReadOnlyXML { + ReadOnlyXML x1 = xml `The Lost World`; + return x1; + } + + // need to discuss + resource function get res8(string id) returns ReadOnlyError { + return error("Value"); + } + + resource function get res9(string id) returns ReadOnlyPrimitiveUnion { + return "value"; + } + + + resource function get res10(string id) returns ReadOnlyBracedUnion { + return "x"; + } + + resource function get res11(string id) returns ReadOnlyRec { + return { + id: "xx", + name: "Kitty" + }; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/response_code.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/response_code.bal index 4091d0d31..08a90ff92 100644 --- a/openapi-cli/src/test/resources/ballerina-to-openapi/response/response_code.bal +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/response_code.bal @@ -1,13 +1,7 @@ import ballerina/http; service /payloadV on new http:Listener(9090) { - resource function post pet() returns http:Continue|http:SwitchingProtocols|http:Ok|http:Created|http:Accepted|http:NonAuthoritativeInformation|http:NoContent| - http:ResetContent|http:PartialContent|http:MultipleChoices|http:MovedPermanently|http:Found|http:SeeOther|http:NotModified|http:UseProxy|http:TemporaryRedirect| - http:PermanentRedirect|http:BadRequest|http:Unauthorized|http:PaymentRequired|http:Forbidden|http:NotFound|http:MethodNotAllowed|http:NotAcceptable| - http:ProxyAuthenticationRequired|http:RequestTimeout|http:Conflict|http:Gone|http:LengthRequired|http:PreconditionFailed|http:PayloadTooLarge| - http:UriTooLong|http:UnsupportedMediaType|http:RangeNotSatisfiable|http:ExpectationFailed|http:UpgradeRequired|http:TooManyRequests| - http:RequestHeaderFieldsTooLarge|http:InternalServerError|http:NotImplemented|http:BadGateway|http:ServiceUnavailable|http:GatewayTimeout| - http:HttpVersionNotSupported { - return {}; + resource function post pet() returns http:Continue|http:SwitchingProtocols|http:Processing|http:EarlyHints|http:Ok|http:Created|http:Accepted|http:NonAuthoritativeInformation|http:NoContent|http:PartialContent|http:MultiStatus|http:AlreadyReported|http:IMUsed|http:MultipleChoices|http:MovedPermanently|http:Found|http:SeeOther|http:NotModified|http:UseProxy|http:TemporaryRedirect|http:PermanentRedirect|http:BadRequest|http:Unauthorized|http:PaymentRequired|http:Forbidden|http:NotFound|http:MethodNotAllowed|http:NotAcceptable|http:ProxyAuthenticationRequired|http:Conflict|http:Gone|http:LengthRequired|http:PreconditionFailed|http:PayloadTooLarge|http:UriTooLong|http:UnsupportedMediaType|http:RangeNotSatisfiable|http:ExpectationFailed|http:MisdirectedRequest|http:UnprocessableEntity|http:Locked|http:FailedDependency|http:TooEarly|http:UpgradeRequired|http:PreconditionRequired|http:TooManyRequests|http:RequestHeaderFieldsTooLarge|http:UnavailableDueToLegalReasons|http:InternalServerError|http:NotImplemented|http:BadGateway|http:ServiceUnavailable|http:HttpVersionNotSupported|http:VariantAlsoNegotiates|http:InsufficientStorage|http:LoopDetected|http:NotExtended|http:NetworkAuthenticationRequired { + return {}; } } diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/same_status_code.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/same_status_code.bal new file mode 100644 index 000000000..2d9c60a7a --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/same_status_code.bal @@ -0,0 +1,19 @@ +import ballerina/http; + +type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; + +type Cat record { + int id; + string name; +}; + +service /payloadV on new http:Listener(9090) { + resource function get testPath() returns boolean|int|string|Pet|Cat|error { + return "test"; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors.bal new file mode 100644 index 000000000..80d9dca42 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +@http:ServiceConfig { + cors: { + allowOrigins: ["*"] + } +} + +service /payloadV on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_with_slash.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_with_slash.bal new file mode 100644 index 000000000..0dd94a1f8 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_with_slash.bal @@ -0,0 +1,20 @@ +import ballerina/http; + +@http:ServiceConfig { + cors: { + allowOrigins: ["*"] + } +} +service / on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_without_base_path.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_without_base_path.bal new file mode 100644 index 000000000..6d9745163 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_config_with_cors_without_base_path.bal @@ -0,0 +1,20 @@ +import ballerina/http; + +@http:ServiceConfig { + cors: { + allowOrigins: ["*"] + } +} +service on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_error_and_internal_server_error.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_error_and_internal_server_error.bal new file mode 100644 index 000000000..769fe2ee2 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_error_and_internal_server_error.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +@http:ServiceConfig { + cors: { + allowOrigins: ["*"] + } +} + +service /payloadV on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|http:InternalServerError|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_same_status_codes.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_same_status_codes.bal new file mode 100644 index 000000000..71ed17e21 --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/service_with_same_status_codes.bal @@ -0,0 +1,24 @@ +import ballerina/http; + public type Pet record { + string name ; + int id; + }; + + public type BadRequestRecord record {| + *http:BadRequest; + string body; + |}; + +service /payloadV on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|http:Ok { + return "Hello, " + name; + } + + resource function post greeting() returns BadRequestRecord|http:BadRequest { + return {}; + } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/response/simple_name_ref.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/response/simple_name_ref.bal new file mode 100644 index 000000000..6c61600ef --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/response/simple_name_ref.bal @@ -0,0 +1,163 @@ +import ballerina/http; + +public type Pet record { + string name; +}; + + +public type ReturnValueIntNil int?; + +public type ReturnValueIntArray int[]; + +public type ReturnValueMapJson map; + +public type ReturnValueMapRec map; + +public type ReturnValueMapString map; + +public type ReturnValueJson json; + +public type ReturnValueXML xml; + +public type ReturnValueError error; + +public type ReturnValuePrimitiveUnion float|int; + +public type Dog record { + string breed; + boolean isBark; +}; + +public type ReturnValueRecUnion Pet|Dog; + +public type ErrorRes http:BadRequest; + +public type ErrorResUnion http:BadRequest|float|int; + +public type ReturnValueStr string; + +public type StrNil string?; + +public type StrArray string[]; + +public type StrIntUnion string|int; + +public type ByteArr byte[]; + +// public type ReturnValueStrNilArray string?[]?; + +// public type ReturnValuePrimitiveUnionArr (string|int)[]; + +// public type ReturnValueNilPrimitiveUnionArr (string|int?)[]?; + +// public type ReturnValueNilPrimitiveUnionArrAlt (string?|int?)[]?; // equivalent to the above case + +service /payloadV on new http:Listener(9090) { + + resource function get lift01(string id) returns ReturnValueStr { + return "Value"; + } + + resource function get lift02(string id) returns ReturnValueIntNil { + return (); + } + + resource function get lift03(string id) returns ReturnValueIntArray { + int[] values = [1, 2]; + return values; + } + + resource function get lift05(string id) returns ReturnValueMapJson { + return {"map": {}}; + } + + resource function get lift06(string id) returns ReturnValueJson { + return { + "name": "test-user" + }; + } + + resource function get lift07(string id) returns ReturnValueMapRec { + return {"map": { + name: "Kitty" + }}; + } + + resource function get lift08(string id) returns ReturnValueMapString { + return {"kitty": "cat"}; + } + + resource function get lift09(string id) returns ReturnValueXML { + ReturnValueXML x1 = xml `The Lost World`; + return x1; + } + + // need to discuss + resource function get lift10(string id) returns ReturnValueError { + return error("Value"); + } + + resource function get lift11(string id) returns ReturnValuePrimitiveUnion { + return 1; + } + + resource function get lift12(string id) returns ReturnValueRecUnion { + return { + name: "Kitty" + }; + } + + resource function get res13(string id) returns ErrorRes { + return { + mediaType: "json" + }; + } + + resource function get res14(string id) returns ErrorResUnion { + return { + mediaType: "json" + }; + } + + resource function get res16(string id) returns StrNil { + return (); + } + + resource function get res17(string id) returns StrArray { + string[] values = ["val1", "val2"]; + return values; + } + +// resource function get res18(string id) returns StrIntUnion { +// return 1; +// } + + resource function get res19(string id) returns ByteArr { + byte[] values = [1, 2]; + return values; + } + + // // not working after new implementation //not supported in Ballerina + // resource function get lift13(string id) returns ReturnValueStrNilArray { + // string?[] values = ["val1", ""]; + // return values; + // } + + // // not working //not supported in Ballerina + // resource function get lift14(string id) returns ReturnValuePrimitiveUnionArr { + // (string|int)[] values = ["val", 1]; + // return values; + // } + + // // not working //not supported in Ballerina + // resource function get lift15(string id) returns ReturnValueNilPrimitiveUnionArr { + // (string|int?)[]? values = ["val", 1, ()]; + // return values; + // } + + // // not working //not supported in Ballerina + // resource function get lift16(string id) returns ReturnValueNilPrimitiveUnionArrAlt { + // (string|int?)[]? values = ["val", 1, ()]; + // return values; + // } +} diff --git a/openapi-cli/src/test/resources/ballerina-to-openapi/unsupported_main_file.bal b/openapi-cli/src/test/resources/ballerina-to-openapi/unsupported_main_file.bal new file mode 100644 index 000000000..5f0d66daa --- /dev/null +++ b/openapi-cli/src/test/resources/ballerina-to-openapi/unsupported_main_file.bal @@ -0,0 +1,5 @@ +import ballerina/io; + +public function main() { + io:print("Hello, World!"); +} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/constraint_import.yaml b/openapi-cli/src/test/resources/constraint_import.yaml new file mode 100644 index 000000000..5abaef1a5 --- /dev/null +++ b/openapi-cli/src/test/resources/constraint_import.yaml @@ -0,0 +1,46 @@ +openapi: 3.0.1 +info: + title: V4 + version: 0.1.0 +servers: + - url: "{server}:{port}/v4" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /pet: + post: + operationId: operation_post_/pet + responses: + "202": + description: Accepted + get: + tags: + - pets + operationId: getPet + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/User" +components: + schemas: + User: + type: object + properties: + name: + type: string + maxLength: 10 + age: + type: integer + Pet: + type: object + properties: + name: + type: string + owned_by: + type: string diff --git a/openapi-cli/src/test/resources/emptyPath.yaml b/openapi-cli/src/test/resources/emptyPath.yaml index afbff51b6..7df57078a 100644 --- a/openapi-cli/src/test/resources/emptyPath.yaml +++ b/openapi-cli/src/test/resources/emptyPath.yaml @@ -3,7 +3,7 @@ info: title: serviceName version: 1.0.0 servers: -- url: /serviceName + - url: http://petstore.openapi.io paths: /user: {} components: {} diff --git a/openapi-cli/src/test/resources/emptyService.yaml b/openapi-cli/src/test/resources/emptyService.yaml index 69f655c56..66e005b93 100644 --- a/openapi-cli/src/test/resources/emptyService.yaml +++ b/openapi-cli/src/test/resources/emptyService.yaml @@ -3,6 +3,6 @@ info: title: serviceName version: 1.0.0 servers: -- url: /serviceName +- url: http://petstore.openapi.io paths: {} components: {} diff --git a/openapi-cli/src/test/resources/expected/emptyPath.bal b/openapi-cli/src/test/resources/expected/emptyPath.bal index 0c2c0c8ee..23312d1f6 100644 --- a/openapi-cli/src/test/resources/expected/emptyPath.bal +++ b/openapi-cli/src/test/resources/expected/emptyPath.bal @@ -1,12 +1,9 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + import ballerina/http; -import ballerina/openapi; -listener http:Listener ep0 = new(9090); +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); -@openapi:ServiceInfo { - contract: "" +service / on ep0 { } - -service / on ep0 { - -} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/expected/emptyService.bal b/openapi-cli/src/test/resources/expected/emptyService.bal index 0c2c0c8ee..23312d1f6 100644 --- a/openapi-cli/src/test/resources/expected/emptyService.bal +++ b/openapi-cli/src/test/resources/expected/emptyService.bal @@ -1,12 +1,9 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + import ballerina/http; -import ballerina/openapi; -listener http:Listener ep0 = new(9090); +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); -@openapi:ServiceInfo { - contract: "" +service / on ep0 { } - -service / on ep0 { - -} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/expected/multiMethodResources.bal b/openapi-cli/src/test/resources/expected/multiMethodResources.bal index 68c2ac117..8535a60f8 100644 --- a/openapi-cli/src/test/resources/expected/multiMethodResources.bal +++ b/openapi-cli/src/test/resources/expected/multiMethodResources.bal @@ -1,22 +1,24 @@ -import ballerina/http; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. -@openapi:ServiceInfo { - contract: "" -} - -service / on ep0 { +import ballerina/http; - resource function get user(http:Caller caller, http:Request req) returns error? { +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +service / on ep0 { + # Get operation for the path /user + # + # + return - Successful + resource function get user() returns json { } - resource function put user(http:Caller caller, http:Request req) returns error? { - + # Put operation for the path /user + # + # + return - Successful + resource function put user() returns json { } - resource function post user(http:Caller caller, http:Request req) returns error? { - + # Post operation for the path /user + # + # + return - Successful + resource function post user() returns OkJson { } - -} \ No newline at end of file +} diff --git a/openapi-cli/src/test/resources/expected/noOperationId.bal b/openapi-cli/src/test/resources/expected/noOperationId.bal index dfedbc885..d8fb76d28 100644 --- a/openapi-cli/src/test/resources/expected/noOperationId.bal +++ b/openapi-cli/src/test/resources/expected/noOperationId.bal @@ -1,20 +1,19 @@ -import ballerina/http; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. -@openapi:ServiceInfo { - contract: "" -} - -service / on ep0 { +import ballerina/http; - resource function get user(http:Caller caller, http:Request req) returns error? { +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +service / on ep0 { + # Description + # + # + return - Successful + resource function get user() returns json { } - - resource function post user(http:Caller caller, http:Request req) returns error? { - + # Description + # + # + return - Successful + resource function post user() returns OkJson { } - -} \ No newline at end of file +} diff --git a/openapi-cli/src/test/resources/expected/nonEmptyPath.bal b/openapi-cli/src/test/resources/expected/nonEmptyPath.bal index e34d90e45..8535a60f8 100644 --- a/openapi-cli/src/test/resources/expected/nonEmptyPath.bal +++ b/openapi-cli/src/test/resources/expected/nonEmptyPath.bal @@ -1,22 +1,24 @@ -import ballerina/http; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. -@openapi:ServiceInfo { - contract: "" -} - -service / on ep0 { +import ballerina/http; - resource function get user(http:Caller caller, http:Request req) returns error? { +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +service / on ep0 { + # Get operation for the path /user + # + # + return - Successful + resource function get user() returns json { } - resource function put user(http:Caller caller, http:Request req) returns error? { - + # Put operation for the path /user + # + # + return - Successful + resource function put user() returns json { } - resource function post user(http:Caller caller, http:Request req) returns error? { - + # Post operation for the path /user + # + # + return - Successful + resource function post user() returns OkJson { } - -} \ No newline at end of file +} diff --git a/openapi-cli/src/test/resources/expected/old_expected/emptyPath.bal b/openapi-cli/src/test/resources/expected/old_expected/emptyPath.bal deleted file mode 100644 index 6a191c05c..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/emptyPath.bal +++ /dev/null @@ -1,26 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); - -@openapi:ServiceInfo { - title: "serviceName", - serviceVersion: "1.0.0" -} -@http:ServiceConfig { - basePath: "/" -} -service serviceName on ep0 { - resource function user (http:Caller outboundEp, http:Request _userReq) { - http:Response _userRes = new; - string _userPayload = "Sample user Response"; - _userRes.setTextPayload(_userPayload); - var result = outboundEp->respond(_userRes); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - -} diff --git a/openapi-cli/src/test/resources/expected/old_expected/emptyService.bal b/openapi-cli/src/test/resources/expected/old_expected/emptyService.bal deleted file mode 100644 index 3c2e5566c..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/emptyService.bal +++ /dev/null @@ -1,17 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); - -@openapi:ServiceInfo { - title: "serviceName", - serviceVersion: "1.0.0" -} -@http:ServiceConfig { - basePath: "/" -} -service serviceName on ep0 { - -} diff --git a/openapi-cli/src/test/resources/expected/old_expected/multiMethodResources.bal b/openapi-cli/src/test/resources/expected/old_expected/multiMethodResources.bal deleted file mode 100644 index 52551e1bd..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/multiMethodResources.bal +++ /dev/null @@ -1,54 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); - -@openapi:ServiceInfo { - title: "serviceName", - serviceVersion: "1.0.0" -} -@http:ServiceConfig { - basePath: "/" -} -service serviceName on ep0 { - - @openapi:MultiResourceInfo { - resourceInformation: { - "GET":{ - summary: "Get operation for the path /user" - }, - "POST":{ - summary: "Post operation for the path /user" - } - } - } - @http:ResourceConfig { - methods:["GET", "POST"], - path:"/user" - } - resource function resource1 (http:Caller outboundEp, http:Request _resource1Req) returns error? { - http:Response _resource1Res = resource1(_resource1Req); - var result = outboundEp->respond(_resource1Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "Put operation for the path /user" - } - @http:ResourceConfig { - methods:["PUT"], - path:"/user" - } - resource function resource2 (http:Caller outboundEp, http:Request _resource2Req) returns error? { - http:Response _resource2Res = resource2(_resource2Req); - var result = outboundEp->respond(_resource2Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - -} diff --git a/openapi-cli/src/test/resources/expected/old_expected/noOperationId.bal b/openapi-cli/src/test/resources/expected/old_expected/noOperationId.bal deleted file mode 100644 index e4e8eec5a..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/noOperationId.bal +++ /dev/null @@ -1,47 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); - -@openapi:ServiceInfo { - title: "serviceName", - serviceVersion: "1.0.0" -} -@http:ServiceConfig { - basePath: "/" -} -service serviceName on ep0 { - - @openapi:ResourceInfo { - summary: "" - } - @http:ResourceConfig { - methods:["GET"], - path:"/user" - } - resource function resource1 (http:Caller outboundEp, http:Request _resource1Req) returns error? { - http:Response _resource1Res = resource1(_resource1Req); - var result = outboundEp->respond(_resource1Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "" - } - @http:ResourceConfig { - methods:["POST"], - path:"/user" - } - resource function resource2 (http:Caller outboundEp, http:Request _resource2Req) returns error? { - http:Response _resource2Res = resource2(_resource2Req); - var result = outboundEp->respond(_resource2Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - -} diff --git a/openapi-cli/src/test/resources/expected/old_expected/nonEmptyPath.bal b/openapi-cli/src/test/resources/expected/old_expected/nonEmptyPath.bal deleted file mode 100644 index f67541090..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/nonEmptyPath.bal +++ /dev/null @@ -1,62 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(9090); - -@openapi:ServiceInfo { - title: "serviceName", - serviceVersion: "1.0.0" -} -@http:ServiceConfig { - basePath: "/" -} -service serviceName on ep0 { - - @openapi:ResourceInfo { - summary: "Get operation for the path /user" - } - @http:ResourceConfig { - methods:["GET"], - path:"/user" - } - resource function resource1 (http:Caller outboundEp, http:Request _resource1Req) returns error? { - http:Response _resource1Res = resource1(_resource1Req); - var result = outboundEp->respond(_resource1Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "Put operation for the path /user" - } - @http:ResourceConfig { - methods:["PUT"], - path:"/user" - } - resource function resource2 (http:Caller outboundEp, http:Request _resource2Req) returns error? { - http:Response _resource2Res = resource2(_resource2Req); - var result = outboundEp->respond(_resource2Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "Post operation for the path /user" - } - @http:ResourceConfig { - methods:["POST"], - path:"/user" - } - resource function resource3 (http:Caller outboundEp, http:Request _resource3Req) returns error? { - http:Response _resource3Res = resource3(_resource3Req); - var result = outboundEp->respond(_resource3Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - -} diff --git a/openapi-cli/src/test/resources/expected/old_expected/petstore.bal b/openapi-cli/src/test/resources/expected/old_expected/petstore.bal deleted file mode 100644 index 2884044fd..000000000 --- a/openapi-cli/src/test/resources/expected/old_expected/petstore.bal +++ /dev/null @@ -1,105 +0,0 @@ -import ballerina/http; -import ballerina/log; -import ballerina/mime; -import ballerina/openapi; - -listener http:Listener ep0 = new(80, config = {host: "petstore.openapi.io"}); - -listener http:Listener ep1 = new(443, config = {host: "petstore.swagger.io"}); - -@openapi:ServiceInfo { - title: "OpenApi Petstore", - serviceVersion: "1.0.0", - license: {name: "MIT", url: ""}, - tags: [ - {name: "pets", description: "Pets Tag", externalDocs: {}}, - {name: "list", description: "List Tag", externalDocs: {}} - ], - security: [ - {name: "petstore_auth", requirements: []}, - {name: "user_auth", requirements: []} - ] -} -@http:ServiceConfig { - basePath: "/v1" -} -service OpenApiPetstore on ep0, ep1 { - resource function action (http:Caller outboundEp, http:Request _actionReq) { - http:Response _actionRes = new; - string _actionPayload = "Sample action Response"; - _actionRes.setTextPayload(_actionPayload); - var result = outboundEp->respond(_actionRes); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "List all pets", - tags: ["pets","list"], - description: "Show a list of pets in the system", - parameters: [ - { - name: "limit", - inInfo: "query", - paramType: "int", - description: "How many items to return at one time (max 100)", - allowEmptyValue: "" - } - ] - } - @http:ResourceConfig { - methods:["GET"], - path:"/pets" - } - resource function listPets (http:Caller outboundEp, http:Request _listPetsReq) returns error? { - http:Response _listPetsRes = listPets(_listPetsReq); - var result = outboundEp->respond(_listPetsRes); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "Create a pet", - tags: ["pets"] - } - @http:ResourceConfig { - methods:["POST"], - path:"/pets" - } - resource function resource1 (http:Caller outboundEp, http:Request _resource1Req) returns error? { - http:Response _resource1Res = resource1(_resource1Req); - var result = outboundEp->respond(_resource1Res); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - - @openapi:ResourceInfo { - summary: "Info for a specific pet", - tags: ["pets"], - parameters: [ - { - name: "petId", - inInfo: "path", - paramType: "string", - description: "The id of the pet to retrieve", - required: true, - allowEmptyValue: "" - } - ] - } - @http:ResourceConfig { - methods:["GET"], - path:"/pets/{petId}" - } - resource function showPetById (http:Caller outboundEp, http:Request _showPetByIdReq, string petId) returns error? { - http:Response _showPetByIdRes = showPetById(_showPetByIdReq, petId); - var result = outboundEp->respond(_showPetByIdRes); - if (result is error) { - log:printError(result.reason(), err = result); - } - } - -} diff --git a/openapi-cli/src/test/resources/expected/petstore.bal b/openapi-cli/src/test/resources/expected/petstore.bal index ef380de16..cf07eea93 100644 --- a/openapi-cli/src/test/resources/expected/petstore.bal +++ b/openapi-cli/src/test/resources/expected/petstore.bal @@ -1,24 +1,32 @@ -import ballerina/http; -import ballerina/openapi; - -listener http:Listener ep0 = new(80, config = {host: "petstore.openapi.io"}); - -listener http:Listener ep1 = new(443, config = {host: "petstore.swagger.io"}); - -@openapi:ServiceInfo { - contract: "" -} +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. -service /v1 on ep0, ep1 { +import ballerina/http; - resource function get pets(http:Caller caller, http:Request req, int limit) returns error? { +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { } - resource function post pets(http:Caller caller, http:Request req) returns error? { - + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) + resource function post pets() returns http:Created|http:Response { } - resource function get pets/[string petId](http:Caller caller, http:Request req) returns error? { - + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { } - -} \ No newline at end of file +} diff --git a/openapi-cli/src/test/resources/expected/petstore_catch_all_path.bal b/openapi-cli/src/test/resources/expected/petstore_catch_all_path.bal new file mode 100644 index 000000000..3adb06f5b --- /dev/null +++ b/openapi-cli/src/test/resources/expected/petstore_catch_all_path.bal @@ -0,0 +1,36 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # Find pet by ID + # + # + petId - ID of pet to return + # + return - returns can be any of following types + # Pet (xml) + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Pet not found) + resource function get \*(int petId) returns Pet|xml|http:BadRequest|http:NotFound { + } + # Update an existing pet + # + # + payload - Update an existent pet in the store + # + return - returns can be any of following types + # Pet (xml) + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Pet not found) + # http:MethodNotAllowed (Validation exception) + resource function put pet(@http:Payload xml|map|Pet payload) returns Pet|xml|http:BadRequest|http:NotFound|http:MethodNotAllowed { + } + # Add a new pet to the store + # + # + payload - Create a new pet in the store + # + return - returns can be any of following types + # OkPetXml (Successful operation) + # http:MethodNotAllowed (Invalid input) + resource function post pet(@http:Payload xml|map|Pet payload) returns OkPetXml|http:MethodNotAllowed { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/allOf-schema-petstore.bal b/openapi-cli/src/test/resources/expected_gen/allOf-schema-petstore.bal index dc9fd19d6..1619b8d6a 100644 --- a/openapi-cli/src/test/resources/expected_gen/allOf-schema-petstore.bal +++ b/openapi-cli/src/test/resources/expected_gen/allOf-schema-petstore.bal @@ -1,14 +1,14 @@ -type Pet record { +type Pet record {| int id; string name; string tag?; string 'type?; -}; -type Dog record { +|}; +type Dog record {| *Pet; boolean bark?; -}; -type Error record { +|}; +type Error record {| int code; string message; -}; \ No newline at end of file +|}; diff --git a/openapi-cli/src/test/resources/expected_gen/ballerina_project/Ballerina.toml b/openapi-cli/src/test/resources/expected_gen/ballerina_project/Ballerina.toml new file mode 100644 index 000000000..423c7ab47 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/ballerina_project/Ballerina.toml @@ -0,0 +1,5 @@ +[package] +org= "ballerina" +name= "testservicegen" +version= "0.0.0" + diff --git a/openapi-cli/src/test/resources/expected_gen/ballerina_project/Package.md b/openapi-cli/src/test/resources/expected_gen/ballerina_project/Package.md new file mode 100644 index 000000000..eccf3700f --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/ballerina_project/Package.md @@ -0,0 +1 @@ +## Package overview diff --git a/openapi-cli/src/test/resources/expected_gen/client_filtered_by_tags.bal b/openapi-cli/src/test/resources/expected_gen/client_filtered_by_tags.bal index 9006591e9..66e775fe7 100644 --- a/openapi-cli/src/test/resources/expected_gen/client_filtered_by_tags.bal +++ b/openapi-cli/src/test/resources/expected_gen/client_filtered_by_tags.bal @@ -1,14 +1,39 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + import ballerina/http; public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -20,7 +45,7 @@ public isolated client class Client { string resourcePath = string `/pets`; map queryParam = {"limit": 'limit}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - Pets response = check self.clientEp-> get(resourcePath); + Pets response = check self.clientEp->get(resourcePath); return response; } # Create a pet @@ -29,7 +54,6 @@ public isolated client class Client { remote isolated function createPet() returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } @@ -39,16 +63,16 @@ public isolated client class Client { # + return - Expected response to a valid request remote isolated function showPetById(string petId) returns Pets|error { string resourcePath = string `/pets/${getEncodedUri(petId)}`; - Pets response = check self.clientEp-> get(resourcePath); + Pets response = check self.clientEp->get(resourcePath); return response; } # Info for a specific pet # - # + dogId - The id of the pet to retrieve + # + dog_id - The id of the pet to retrieve # + return - Expected response to a valid request - remote isolated function getDogs(string dogId) returns Dog|error { - string resourcePath = string `/pets/dogs/${getEncodedUri(dogId)}`; - Dog response = check self.clientEp-> get(resourcePath); + remote isolated function getDogs(string dog_id) returns Dog|error { + string resourcePath = string `/pets/dogs/${getEncodedUri(dog_id)}`; + Dog response = check self.clientEp->get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/expected_gen/constraint_import_types.bal b/openapi-cli/src/test/resources/expected_gen/constraint_import_types.bal new file mode 100644 index 000000000..a68b3bcac --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/constraint_import_types.bal @@ -0,0 +1,67 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/constraint; +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type User record { + @constraint:String {maxLength: 10} + string name?; + int age?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/generateSkeleton.bal b/openapi-cli/src/test/resources/expected_gen/generateSkeleton.bal index 22afa5722..168cb3918 100644 --- a/openapi-cli/src/test/resources/expected_gen/generateSkeleton.bal +++ b/openapi-cli/src/test/resources/expected_gen/generateSkeleton.bal @@ -1,13 +1,29 @@ +import ballerina/http; -import ballerina/http; +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); -listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); - - service /v1 on ep0 { - resource function get pets(int? 'limit) returns Pets|http:Response { +service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { } - resource function post pets() returns http:Created|http:Response { + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) + resource function post pets() returns http:Created|http:Response { } - resource function get pets/[string petId]() returns Pets|http:Response { + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/expected_gen/generate_client.bal b/openapi-cli/src/test/resources/expected_gen/generate_client.bal index f0ecd0862..623a002b9 100644 --- a/openapi-cli/src/test/resources/expected_gen/generate_client.bal +++ b/openapi-cli/src/test/resources/expected_gen/generate_client.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -29,7 +51,6 @@ public isolated client class Client { remote isolated function createPet() returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/expected_gen/generate_client_requestbody.bal b/openapi-cli/src/test/resources/expected_gen/generate_client_requestbody.bal index eba881f2c..67c2c5632 100644 --- a/openapi-cli/src/test/resources/expected_gen/generate_client_requestbody.bal +++ b/openapi-cli/src/test/resources/expected_gen/generate_client_requestbody.bal @@ -1,15 +1,37 @@ -import ballerina/http; +import ballerina/http; # refComponent public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -19,9 +41,9 @@ public isolated client class Client { remote isolated function createUser(User payload) returns http:Response|error { string resourcePath = string `/requestBody`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); - http:Response response = check self.clientEp-> post(resourcePath, request); + http:Response response = check self.clientEp->post(resourcePath, request); return response; } } diff --git a/openapi-cli/src/test/resources/expected_gen/generatedRB.bal b/openapi-cli/src/test/resources/expected_gen/generatedRB.bal index 5450feaff..677758dce 100644 --- a/openapi-cli/src/test/resources/expected_gen/generatedRB.bal +++ b/openapi-cli/src/test/resources/expected_gen/generatedRB.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service / on ep0 { + # Creates a new user. + # + # + payload - parameter description + # + return - OK resource function post requestBody(@http:Payload User payload) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/expected_gen/generated_bal.bal b/openapi-cli/src/test/resources/expected_gen/generated_bal.bal index f68989216..505cdc19a 100644 --- a/openapi-cli/src/test/resources/expected_gen/generated_bal.bal +++ b/openapi-cli/src/test/resources/expected_gen/generated_bal.bal @@ -3,6 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + petName - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) resource function get pets/[string petId]/petName/[string petName]() returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/expected_gen/generated_client_with_license.bal b/openapi-cli/src/test/resources/expected_gen/generated_client_with_license.bal index dd91ab1d0..01be188ed 100644 --- a/openapi-cli/src/test/resources/expected_gen/generated_client_with_license.bal +++ b/openapi-cli/src/test/resources/expected_gen/generated_client_with_license.bal @@ -1,17 +1,37 @@ // Copyright (c) 2021 All Rights Reserved. -import ballerina/http; - +import ballerina/http; public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -19,20 +39,19 @@ public isolated client class Client { # # + 'limit - How many items to return at one time (max 100) # + return - An paged array of pets - remote isolated function listPets(int? 'limit = ()) returns Pets|error { + resource isolated function get pets(int? 'limit = ()) returns Pets|error { string resourcePath = string `/pets`; map queryParam = {"limit": 'limit}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - Pets response = check self.clientEp-> get(resourcePath); + Pets response = check self.clientEp->get(resourcePath); return response; } # Create a pet # # + return - Null response - remote isolated function createPet() returns http:Response|error { + resource isolated function post pets() returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } @@ -40,11 +59,9 @@ public isolated client class Client { # # + petId - The id of the pet to retrieve # + return - Expected response to a valid request - remote isolated function showPetById(string petId) returns Pets|error { + resource isolated function get pets/[string petId]() returns Pets|error { string resourcePath = string `/pets/${getEncodedUri(petId)}`; - Pets response = check self.clientEp-> get(resourcePath); + Pets response = check self.clientEp->get(resourcePath); return response; } } - - diff --git a/openapi-cli/src/test/resources/expected_gen/generic_service_petstore.bal b/openapi-cli/src/test/resources/expected_gen/generic_service_petstore.bal new file mode 100644 index 000000000..907d43b8b --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/generic_service_petstore.bal @@ -0,0 +1,15 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + resource function get pets(http:Caller caller, http:Request request) returns error? { + } + resource function post pets(http:Caller caller, http:Request request) returns error? { + } + resource function get pets/[string petId](http:Caller caller, http:Request request) returns error? { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/generic_service_petstore_original.bal b/openapi-cli/src/test/resources/expected_gen/generic_service_petstore_original.bal new file mode 100644 index 000000000..a294c26d2 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/generic_service_petstore_original.bal @@ -0,0 +1,44 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + resource function put pet(http:Caller caller, http:Request request) returns error? { + } + resource function post pet(http:Caller caller, http:Request request) returns error? { + } + resource function get pet/findByStatus(http:Caller caller, http:Request request) returns error? { + } + resource function get pet/findByTags(http:Caller caller, http:Request request) returns error? { + } + resource function get pet/[int petId](http:Caller caller, http:Request request) returns error? { + } + resource function post pet/[int petId](http:Caller caller, http:Request request) returns error? { + } + resource function delete pet/[int petId](http:Caller caller, http:Request request) returns error? { + } + resource function post pet/[int petId]/uploadImage(http:Caller caller, http:Request request) returns error? { + } + resource function get store/inventory(http:Caller caller, http:Request request) returns error? { + } + resource function post store/'order(http:Caller caller, http:Request request) returns error? { + } + resource function get store/'order/[int orderId](http:Caller caller, http:Request request) returns error? { + } + resource function delete store/'order/[int orderId](http:Caller caller, http:Request request) returns error? { + } + resource function post user(http:Caller caller, http:Request request) returns error? { + } + resource function post user/createWithList(http:Caller caller, http:Request request) returns error? { + } + resource function get user/login(http:Caller caller, http:Request request) returns error? { + } + resource function get user/logout(http:Caller caller, http:Request request) returns error? { + } + resource function get user/[string username](http:Caller caller, http:Request request) returns error? { + } + resource function put user/[string username](http:Caller caller, http:Request request) returns error? { + } + resource function delete user/[string username](http:Caller caller, http:Request request) returns error? { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/client.bal b/openapi-cli/src/test/resources/expected_gen/licenses/client.bal new file mode 100644 index 000000000..656748aa5 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/client.bal @@ -0,0 +1,69 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - An paged array of pets + resource isolated function get pets(int? 'limit = ()) returns Pets|error { + string resourcePath = string `/pets`; + map queryParam = {"limit": 'limit}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + Pets response = check self.clientEp->get(resourcePath); + return response; + } + # Create a pet + # + # + return - Null response + resource isolated function post pets() returns http:Response|error { + string resourcePath = string `/pets`; + http:Request request = new; + http:Response response = check self.clientEp-> post(resourcePath, request); + return response; + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - Expected response to a valid request + resource isolated function get pets/[string petId]() returns Pets|error { + string resourcePath = string `/pets/${getEncodedUri(petId)}`; + Pets response = check self.clientEp->get(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/client_with_user_given_license.bal b/openapi-cli/src/test/resources/expected_gen/licenses/client_with_user_given_license.bal new file mode 100644 index 000000000..960c79740 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/client_with_user_given_license.bal @@ -0,0 +1,68 @@ +// Copyright (c) 2023 All Rights Reserved. + +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - An paged array of pets + resource isolated function get pets(int? 'limit = ()) returns Pets|error { + string resourcePath = string `/pets`; + map queryParam = {"limit": 'limit}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + Pets response = check self.clientEp->get(resourcePath); + return response; + } + # Create a pet + # + # + return - Null response + resource isolated function post pets() returns http:Response|error { + string resourcePath = string `/pets`; + http:Request request = new; + http:Response response = check self.clientEp-> post(resourcePath, request); + return response; + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - Expected response to a valid request + resource isolated function get pets/[string petId]() returns Pets|error { + string resourcePath = string `/pets/${getEncodedUri(petId)}`; + Pets response = check self.clientEp->get(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/license.txt b/openapi-cli/src/test/resources/expected_gen/licenses/license.txt new file mode 100644 index 000000000..616110565 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/license.txt @@ -0,0 +1 @@ +// Copyright (c) 2023 All Rights Reserved. \ No newline at end of file diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/schema.bal b/openapi-cli/src/test/resources/expected_gen/licenses/schema.bal new file mode 100644 index 000000000..0ff7c7247 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/schema.bal @@ -0,0 +1,79 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_both_service_client.bal b/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_both_service_client.bal new file mode 100644 index 000000000..d835819c6 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_both_service_client.bal @@ -0,0 +1,79 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_service.bal b/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_service.bal new file mode 100644 index 000000000..ac33e05a5 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/schema_for_service.bal @@ -0,0 +1,21 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/schema_with_user_given_license.bal b/openapi-cli/src/test/resources/expected_gen/licenses/schema_with_user_given_license.bal new file mode 100644 index 000000000..caa35e690 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/schema_with_user_given_license.bal @@ -0,0 +1,78 @@ +// Copyright (c) 2023 All Rights Reserved. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/service.bal b/openapi-cli/src/test/resources/expected_gen/licenses/service.bal new file mode 100644 index 000000000..cf07eea93 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/service.bal @@ -0,0 +1,32 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { + } + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) + resource function post pets() returns http:Created|http:Response { + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/service_type.bal b/openapi-cli/src/test/resources/expected_gen/licenses/service_type.bal new file mode 100644 index 000000000..cebef7b34 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/service_type.bal @@ -0,0 +1,11 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +type OASServiceType service object { + *http:Service; + resource function get pets(int? 'limit) returns Pets|http:Response; + resource function post pets() returns http:Created|http:Response; + resource function get pets/[string petId]() returns Pets|http:Response; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/service_type_with_user_given_license.bal b/openapi-cli/src/test/resources/expected_gen/licenses/service_type_with_user_given_license.bal new file mode 100644 index 000000000..84902ddbd --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/service_type_with_user_given_license.bal @@ -0,0 +1,10 @@ +// Copyright (c) 2023 All Rights Reserved. + +import ballerina/http; + +type OASServiceType service object { + *http:Service; + resource function get pets(int? 'limit) returns Pets|http:Response; + resource function post pets() returns http:Created|http:Response; + resource function get pets/[string petId]() returns Pets|http:Response; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/service_with_service_type.bal b/openapi-cli/src/test/resources/expected_gen/licenses/service_with_service_type.bal new file mode 100644 index 000000000..5bfd11040 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/service_with_service_type.bal @@ -0,0 +1,32 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service OASServiceType /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { + } + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) + resource function post pets() returns http:Created|http:Response { + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/service_with_user_given_license.bal b/openapi-cli/src/test/resources/expected_gen/licenses/service_with_user_given_license.bal new file mode 100644 index 000000000..8df800291 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/service_with_user_given_license.bal @@ -0,0 +1,31 @@ +// Copyright (c) 2023 All Rights Reserved. + +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service OASServiceType /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { + } + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) + resource function post pets() returns http:Created|http:Response { + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/types_for_both_service_client_generations.bal b/openapi-cli/src/test/resources/expected_gen/licenses/types_for_both_service_client_generations.bal new file mode 100644 index 000000000..d835819c6 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/types_for_both_service_client_generations.bal @@ -0,0 +1,79 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_both_service_client_generation.bal b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_both_service_client_generation.bal new file mode 100644 index 000000000..31fb375dc --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_both_service_client_generation.bal @@ -0,0 +1,201 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/url; + +type SimpleBasicType string|boolean|int|float|decimal; + +# Represents encoding mechanism details. +type Encoding record { + # Defines how multiple values are delimited + string style = FORM; + # Specifies whether arrays and objects should generate as separate fields + boolean explode = true; + # Specifies the custom content type + string contentType?; + # Specifies the custom headers + map headers?; +}; + +enum EncodingStyle { + DEEPOBJECT, FORM, SPACEDELIMITED, PIPEDELIMITED +} + +final Encoding & readonly defaultEncoding = {}; + +# Serialize the record according to the deepObject style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + return - Serialized record as a string +isolated function getDeepObjectStyleRequest(string parent, record {} anyRecord) returns string { + string[] recordArray = []; + foreach [string, anydata] [key, value] in anyRecord.entries() { + if value is SimpleBasicType { + recordArray.push(parent + "[" + key + "]" + "=" + getEncodedUri(value.toString())); + } else if value is SimpleBasicType[] { + recordArray.push(getSerializedArray(parent + "[" + key + "]" + "[]", value, DEEPOBJECT, true)); + } else if value is record {} { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getDeepObjectStyleRequest(nextParent, value)); + } else if value is record {}[] { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getSerializedRecordArray(nextParent, value, DEEPOBJECT)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + return string:'join("", ...recordArray); +} + +# Serialize the record according to the form style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getFormStyleRequest(string parent, record {} anyRecord, boolean explode = true) returns string { + string[] recordArray = []; + if explode { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = explode)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + } else { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, ",", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = false)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push(","); + } + _ = recordArray.pop(); + } + return string:'join("", ...recordArray); +} + +# Serialize arrays. +# +# + arrayName - Name of the field with arrays +# + anyArray - Array to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized array as a string +isolated function getSerializedArray(string arrayName, anydata[] anyArray, string style = "form", boolean explode = true) returns string { + string key = arrayName; + string[] arrayValues = []; + if (anyArray.length() > 0) { + if (style == FORM && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), ","); + } + } else if (style == SPACEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "%20"); + } + } else if (style == PIPEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "|"); + } + } else if (style == DEEPOBJECT) { + foreach anydata i in anyArray { + arrayValues.push(key, "[]", "=", getEncodedUri(i.toString()), "&"); + } + } else { + foreach anydata i in anyArray { + arrayValues.push(key, "=", getEncodedUri(i.toString()), "&"); + } + } + _ = arrayValues.pop(); + } + return string:'join("", ...arrayValues); +} + +# Serialize the array of records according to the form style. +# +# + parent - Parent record name +# + value - Array of records to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getSerializedRecordArray(string parent, record {}[] value, string style = FORM, boolean explode = true) returns string { + string[] serializedArray = []; + if style == DEEPOBJECT { + int arayIndex = 0; + foreach var recordItem in value { + serializedArray.push(getDeepObjectStyleRequest(parent + "[" + arayIndex.toString() + "]", recordItem), "&"); + arayIndex = arayIndex + 1; + } + } else { + if (!explode) { + serializedArray.push(parent, "="); + } + foreach var recordItem in value { + serializedArray.push(getFormStyleRequest(parent, recordItem, explode), ","); + } + } + _ = serializedArray.pop(); + return string:'join("", ...serializedArray); +} + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +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 +# + encodingMap - Details on serialization mechanism +# + return - Returns generated Path or error at failure of client initialization +isolated function getPathForQueryParam(map queryParam, map encodingMap = {}) 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; + } + Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : defaultEncoding; + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + param.push(getSerializedArray(key, value, encodingData.style, encodingData.explode)); + } else if (value is record {}) { + if (encodingData.style == DEEPOBJECT) { + param.push(getDeepObjectStyleRequest(key, value)); + } else { + param.push(getFormStyleRequest(key, value, encodingData.explode)); + } + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_client_generation.bal b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_client_generation.bal new file mode 100644 index 000000000..c8e31de56 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_client_generation.bal @@ -0,0 +1,201 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/url; + +type SimpleBasicType string|boolean|int|float|decimal; + +# Represents encoding mechanism details. +type Encoding record { + # Defines how multiple values are delimited + string style = FORM; + # Specifies whether arrays and objects should generate as separate fields + boolean explode = true; + # Specifies the custom content type + string contentType?; + # Specifies the custom headers + map headers?; +}; + +enum EncodingStyle { + DEEPOBJECT, FORM, SPACEDELIMITED, PIPEDELIMITED +} + +final Encoding & readonly defaultEncoding = {}; + +# Serialize the record according to the deepObject style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + return - Serialized record as a string +isolated function getDeepObjectStyleRequest(string parent, record {} anyRecord) returns string { + string[] recordArray = []; + foreach [string, anydata] [key, value] in anyRecord.entries() { + if value is SimpleBasicType { + recordArray.push(parent + "[" + key + "]" + "=" + getEncodedUri(value.toString())); + } else if value is SimpleBasicType[] { + recordArray.push(getSerializedArray(parent + "[" + key + "]" + "[]", value, DEEPOBJECT, true)); + } else if value is record {} { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getDeepObjectStyleRequest(nextParent, value)); + } else if value is record {}[] { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getSerializedRecordArray(nextParent, value, DEEPOBJECT)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + return string:'join("", ...recordArray); +} + +# Serialize the record according to the form style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getFormStyleRequest(string parent, record {} anyRecord, boolean explode = true) returns string { + string[] recordArray = []; + if explode { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = explode)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + } else { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, ",", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = false)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push(","); + } + _ = recordArray.pop(); + } + return string:'join("", ...recordArray); +} + +# Serialize arrays. +# +# + arrayName - Name of the field with arrays +# + anyArray - Array to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized array as a string +isolated function getSerializedArray(string arrayName, anydata[] anyArray, string style = "form", boolean explode = true) returns string { + string key = arrayName; + string[] arrayValues = []; + if (anyArray.length() > 0) { + if (style == FORM && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), ","); + } + } else if (style == SPACEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "%20"); + } + } else if (style == PIPEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "|"); + } + } else if (style == DEEPOBJECT) { + foreach anydata i in anyArray { + arrayValues.push(key, "[]", "=", getEncodedUri(i.toString()), "&"); + } + } else { + foreach anydata i in anyArray { + arrayValues.push(key, "=", getEncodedUri(i.toString()), "&"); + } + } + _ = arrayValues.pop(); + } + return string:'join("", ...arrayValues); +} + +# Serialize the array of records according to the form style. +# +# + parent - Parent record name +# + value - Array of records to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getSerializedRecordArray(string parent, record {}[] value, string style = FORM, boolean explode = true) returns string { + string[] serializedArray = []; + if style == DEEPOBJECT { + int arayIndex = 0; + foreach var recordItem in value { + serializedArray.push(getDeepObjectStyleRequest(parent + "[" + arayIndex.toString() + "]", recordItem), "&"); + arayIndex = arayIndex + 1; + } + } else { + if (!explode) { + serializedArray.push(parent, "="); + } + foreach var recordItem in value { + serializedArray.push(getFormStyleRequest(parent, recordItem, explode), ","); + } + } + _ = serializedArray.pop(); + return string:'join("", ...serializedArray); +} + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +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 +# + encodingMap - Details on serialization mechanism +# + return - Returns generated Path or error at failure of client initialization +isolated function getPathForQueryParam(map queryParam, map encodingMap = {}) 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; + } + Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : defaultEncoding; + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + param.push(getSerializedArray(key, value, encodingData.style, encodingData.explode)); + } else if (value is record {}) { + if (encodingData.style == DEEPOBJECT) { + param.push(getDeepObjectStyleRequest(key, value)); + } else { + param.push(getFormStyleRequest(key, value, encodingData.explode)); + } + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} diff --git a/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_with_user_given_license.bal b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_with_user_given_license.bal new file mode 100644 index 000000000..98b9b6987 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/licenses/utils_for_with_user_given_license.bal @@ -0,0 +1,200 @@ +// Copyright (c) 2023 All Rights Reserved. + +import ballerina/url; + +type SimpleBasicType string|boolean|int|float|decimal; + +# Represents encoding mechanism details. +type Encoding record { + # Defines how multiple values are delimited + string style = FORM; + # Specifies whether arrays and objects should generate as separate fields + boolean explode = true; + # Specifies the custom content type + string contentType?; + # Specifies the custom headers + map headers?; +}; + +enum EncodingStyle { + DEEPOBJECT, FORM, SPACEDELIMITED, PIPEDELIMITED +} + +final Encoding & readonly defaultEncoding = {}; + +# Serialize the record according to the deepObject style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + return - Serialized record as a string +isolated function getDeepObjectStyleRequest(string parent, record {} anyRecord) returns string { + string[] recordArray = []; + foreach [string, anydata] [key, value] in anyRecord.entries() { + if value is SimpleBasicType { + recordArray.push(parent + "[" + key + "]" + "=" + getEncodedUri(value.toString())); + } else if value is SimpleBasicType[] { + recordArray.push(getSerializedArray(parent + "[" + key + "]" + "[]", value, DEEPOBJECT, true)); + } else if value is record {} { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getDeepObjectStyleRequest(nextParent, value)); + } else if value is record {}[] { + string nextParent = parent + "[" + key + "]"; + recordArray.push(getSerializedRecordArray(nextParent, value, DEEPOBJECT)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + return string:'join("", ...recordArray); +} + +# Serialize the record according to the form style. +# +# + parent - Parent record name +# + anyRecord - Record to be serialized +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getFormStyleRequest(string parent, record {} anyRecord, boolean explode = true) returns string { + string[] recordArray = []; + if explode { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = explode)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push("&"); + } + _ = recordArray.pop(); + } else { + foreach [string, anydata] [key, value] in anyRecord.entries() { + if (value is SimpleBasicType) { + recordArray.push(key, ",", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + recordArray.push(getSerializedArray(key, value, explode = false)); + } else if (value is record {}) { + recordArray.push(getFormStyleRequest(parent, value, explode)); + } + recordArray.push(","); + } + _ = recordArray.pop(); + } + return string:'join("", ...recordArray); +} + +# Serialize arrays. +# +# + arrayName - Name of the field with arrays +# + anyArray - Array to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized array as a string +isolated function getSerializedArray(string arrayName, anydata[] anyArray, string style = "form", boolean explode = true) returns string { + string key = arrayName; + string[] arrayValues = []; + if (anyArray.length() > 0) { + if (style == FORM && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), ","); + } + } else if (style == SPACEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "%20"); + } + } else if (style == PIPEDELIMITED && !explode) { + arrayValues.push(key, "="); + foreach anydata i in anyArray { + arrayValues.push(getEncodedUri(i.toString()), "|"); + } + } else if (style == DEEPOBJECT) { + foreach anydata i in anyArray { + arrayValues.push(key, "[]", "=", getEncodedUri(i.toString()), "&"); + } + } else { + foreach anydata i in anyArray { + arrayValues.push(key, "=", getEncodedUri(i.toString()), "&"); + } + } + _ = arrayValues.pop(); + } + return string:'join("", ...arrayValues); +} + +# Serialize the array of records according to the form style. +# +# + parent - Parent record name +# + value - Array of records to be serialized +# + style - Defines how multiple values are delimited +# + explode - Specifies whether arrays and objects should generate separate parameters +# + return - Serialized record as a string +isolated function getSerializedRecordArray(string parent, record {}[] value, string style = FORM, boolean explode = true) returns string { + string[] serializedArray = []; + if style == DEEPOBJECT { + int arayIndex = 0; + foreach var recordItem in value { + serializedArray.push(getDeepObjectStyleRequest(parent + "[" + arayIndex.toString() + "]", recordItem), "&"); + arayIndex = arayIndex + 1; + } + } else { + if (!explode) { + serializedArray.push(parent, "="); + } + foreach var recordItem in value { + serializedArray.push(getFormStyleRequest(parent, recordItem, explode), ","); + } + } + _ = serializedArray.pop(); + return string:'join("", ...serializedArray); +} + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +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 +# + encodingMap - Details on serialization mechanism +# + return - Returns generated Path or error at failure of client initialization +isolated function getPathForQueryParam(map queryParam, map encodingMap = {}) 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; + } + Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : defaultEncoding; + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + } else if (value is SimpleBasicType[]) { + param.push(getSerializedArray(key, value, encodingData.style, encodingData.explode)); + } else if (value is record {}) { + if (encodingData.style == DEEPOBJECT) { + param.push(getDeepObjectStyleRequest(key, value)); + } else { + param.push(getFormStyleRequest(key, value, encodingData.explode)); + } + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} diff --git a/openapi-cli/src/test/resources/expected_gen/multi_query_para.bal b/openapi-cli/src/test/resources/expected_gen/multi_query_para.bal index 035f71991..b9b392a8b 100644 --- a/openapi-cli/src/test/resources/expected_gen/multi_query_para.bal +++ b/openapi-cli/src/test/resources/expected_gen/multi_query_para.bal @@ -1,8 +1,15 @@ -import ballerina/http; +import ballerina/http; -listener http:Listener ep0 = new (80, config = {host: "petstore.swagger.io"}); +listener http:Listener ep0 = new (80, config = {host: "petstore.swagger.io"}); - service /api on ep0 { - resource function get pets(string[]? tags, int? 'limit) returns Pet[]|http:Response { +service /api on ep0 { + # Returns all pets from the system that the user has access + # + # + tags - tags to filter by + # + 'limit - maximum number of results to return + # + return - returns can be any of following types + # Pet[] (pet response) + # http:Response (unexpected error) + resource function get pets(string[]? tags, int? 'limit) returns Pet[]|http:Response { } } diff --git a/openapi-cli/src/test/resources/expected_gen/non_constraint_import_types.bal b/openapi-cli/src/test/resources/expected_gen/non_constraint_import_types.bal new file mode 100644 index 000000000..f5524065f --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/non_constraint_import_types.bal @@ -0,0 +1,65 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Pet record { + string name?; + string owned_by?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/pestore_service_type.bal b/openapi-cli/src/test/resources/expected_gen/pestore_service_type.bal new file mode 100644 index 000000000..cebef7b34 --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/pestore_service_type.bal @@ -0,0 +1,11 @@ +// AUTO-GENERATED FILE. DO NOT MODIFY. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +type OASServiceType service object { + *http:Service; + resource function get pets(int? 'limit) returns Pets|http:Response; + resource function post pets() returns http:Created|http:Response; + resource function get pets/[string petId]() returns Pets|http:Response; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/petstoreOperation.bal b/openapi-cli/src/test/resources/expected_gen/petstoreOperation.bal index 0b40122e8..a4a2b3311 100644 --- a/openapi-cli/src/test/resources/expected_gen/petstoreOperation.bal +++ b/openapi-cli/src/test/resources/expected_gen/petstoreOperation.bal @@ -1,10 +1,22 @@ -import ballerina/http; +import ballerina/http; -listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); - service /v1 on ep0 { - resource function get pets(int? 'limit) returns Pets|http:Response { +service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { } - resource function get pets/[string petId]() returns Pets|http:Response { + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets/[string petId]() returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/expected_gen/petstoreTag.bal b/openapi-cli/src/test/resources/expected_gen/petstoreTag.bal index 3531e83b2..efbe11b78 100644 --- a/openapi-cli/src/test/resources/expected_gen/petstoreTag.bal +++ b/openapi-cli/src/test/resources/expected_gen/petstoreTag.bal @@ -1,8 +1,14 @@ -import ballerina/http; +import ballerina/http; -listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); - service /v1 on ep0 { - resource function get pets(int? 'limit) returns Pets|http:Response { +service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_catch_all_path_client.bal b/openapi-cli/src/test/resources/expected_gen/petstore_catch_all_path_client.bal new file mode 100644 index 000000000..f0235075b --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/petstore_catch_all_path_client.bal @@ -0,0 +1,85 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. +public isolated client class Client { + final http:Client clientEp; + final readonly & ApiKeysConfig? apiKeyConfig; + # 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(ConnectionConfig config, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + if config.auth is ApiKeysConfig { + self.apiKeyConfig = (config.auth).cloneReadOnly(); + } else { + config.auth = config.auth; + self.apiKeyConfig = (); + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Find pet by ID + # + # + petId - ID of pet to return + # + return - successful operation + resource isolated function get \*(int petId) returns Pet|error { + string resourcePath = string `/*`; + map headerValues = {}; + map queryParam = {"petId": petId}; + if self.apiKeyConfig is ApiKeysConfig { + headerValues["api_key"] = self.apiKeyConfig?.api_key; + } + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + map httpHeaders = getMapForHeaders(headerValues); + Pet response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } + # Update an existing pet + # + # + payload - Update an existent pet in the store + # + return - Successful operation + resource isolated function put pet(Pet payload) returns Pet|error { + string resourcePath = string `/pet`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + Pet response = check self.clientEp->put(resourcePath, request); + return response; + } + # Add a new pet to the store + # + # + payload - Create a new pet in the store + # + return - Successful operation + resource isolated function post pet(Pet payload) returns Pet|error { + string resourcePath = string `/pet`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + Pet response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_client_swagger.bal b/openapi-cli/src/test/resources/expected_gen/petstore_client_swagger.bal new file mode 100644 index 000000000..3fc08cbee --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/petstore_client_swagger.bal @@ -0,0 +1,266 @@ +import ballerina/http; +import ballerina/mime; + +# This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +public isolated client class Client { + final http:Client clientEp; + final readonly & ApiKeysConfig? apiKeyConfig; + # 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(ConnectionConfig config, string serviceUrl = "https://petstore.swagger.io/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + if config.auth is ApiKeysConfig { + self.apiKeyConfig = (config.auth).cloneReadOnly(); + } else { + config.auth = config.auth; + self.apiKeyConfig = (); + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Update an existing pet + # + # + payload - Pet object that needs to be added to the store + # + return - Invalid ID supplied + remote isolated function updatePet(Pet payload) returns http:Response|error { + string resourcePath = string `/pet`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + http:Response response = check self.clientEp->put(resourcePath, request); + return response; + } + # Add a new pet to the store + # + # + payload - Pet object that needs to be added to the store + # + return - Invalid input + remote isolated function addPet(Pet payload) returns http:Response|error { + string resourcePath = string `/pet`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Finds Pets by status + # + # + status - Status values that need to be considered for filter + # + return - successful operation + remote isolated function findPetsByStatus(("available"|"pending"|"sold")[] status) returns Pet[]|error { + string resourcePath = string `/pet/findByStatus`; + map queryParam = {"status": status}; + map queryParamEncoding = {"status": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + Pet[] response = check self.clientEp->get(resourcePath); + return response; + } + # Finds Pets by tags + # + # + tags - Tags to filter by + # + return - successful operation + # + # # Deprecated + @deprecated + remote isolated function findPetsByTags(string[] tags) returns Pet[]|error { + string resourcePath = string `/pet/findByTags`; + map queryParam = {"tags": tags}; + map queryParamEncoding = {"tags": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + Pet[] response = check self.clientEp->get(resourcePath); + return response; + } + # Find pet by ID + # + # + petId - ID of pet to return + # + return - successful operation + remote isolated function getPetById(int petId) returns Pet|error { + string resourcePath = string `/pet/${getEncodedUri(petId)}`; + map headerValues = {}; + if self.apiKeyConfig is ApiKeysConfig { + headerValues["api_key"] = self.apiKeyConfig?.api_key; + } + map httpHeaders = getMapForHeaders(headerValues); + Pet response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } + # Updates a pet in the store with form data + # + # + petId - ID of pet that needs to be updated + # + return - Invalid input + remote isolated function updatePetWithForm(int petId, Pet_petId_body payload) returns http:Response|error { + string resourcePath = string `/pet/${getEncodedUri(petId)}`; + http:Request request = new; + string encodedRequestBody = createFormURLEncodedRequestBody(payload); + request.setPayload(encodedRequestBody, "application/x-www-form-urlencoded"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Deletes a pet + # + # + petId - Pet id to delete + # + return - Invalid ID supplied + remote isolated function deletePet(int petId, string? api_key = ()) returns http:Response|error { + string resourcePath = string `/pet/${getEncodedUri(petId)}`; + map headerValues = {"api_key": api_key}; + map httpHeaders = getMapForHeaders(headerValues); + http:Response response = check self.clientEp->delete(resourcePath, headers = httpHeaders); + return response; + } + # uploads an image + # + # + petId - ID of pet to update + # + return - successful operation + remote isolated function uploadFile(int petId, PetId_uploadImage_body payload) returns ApiResponse|error { + string resourcePath = string `/pet/${getEncodedUri(petId)}/uploadImage`; + http:Request request = new; + mime:Entity[] bodyParts = check createBodyParts(payload); + request.setBodyParts(bodyParts); + ApiResponse response = check self.clientEp->post(resourcePath, request); + return response; + } + # Returns pet inventories by status + # + # + return - successful operation + remote isolated function getInventory() returns json|error { + string resourcePath = string `/store/inventory`; + map headerValues = {}; + if self.apiKeyConfig is ApiKeysConfig { + headerValues["api_key"] = self.apiKeyConfig?.api_key; + } + map httpHeaders = getMapForHeaders(headerValues); + json response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } + # Place an order for a pet + # + # + request - order placed for purchasing the pet + # + return - successful operation + remote isolated function placeOrder(http:Request request) returns Order|error { + string resourcePath = string `/store/order`; + // TODO: Update the request as needed; + Order response = check self.clientEp->post(resourcePath, request); + return response; + } + # Find purchase order by ID + # + # + orderId - ID of pet that needs to be fetched + # + return - successful operation + remote isolated function getOrderById(int orderId) returns Order|error { + string resourcePath = string `/store/order/${getEncodedUri(orderId)}`; + Order response = check self.clientEp->get(resourcePath); + return response; + } + # Delete purchase order by ID + # + # + orderId - ID of the order that needs to be deleted + # + return - Invalid ID supplied + remote isolated function deleteOrder(int orderId) returns http:Response|error { + string resourcePath = string `/store/order/${getEncodedUri(orderId)}`; + http:Response response = check self.clientEp-> delete(resourcePath); + return response; + } + # Create user + # + # + request - Created user object + # + return - successful operation + remote isolated function createUser(http:Request request) returns http:Response|error { + string resourcePath = string `/user`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Creates list of users with given input array + # + # + request - List of user object + # + return - successful operation + remote isolated function createUsersWithArrayInput(http:Request request) returns http:Response|error { + string resourcePath = string `/user/createWithArray`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Creates list of users with given input array + # + # + request - List of user object + # + return - successful operation + remote isolated function createUsersWithListInput(http:Request request) returns http:Response|error { + string resourcePath = string `/user/createWithList`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Logs user into the system + # + # + username - The user name for login + # + password - The password for login in clear text + # + return - successful operation + remote isolated function loginUser(string username, string password) returns string|error { + string resourcePath = string `/user/login`; + map queryParam = {"username": username, "password": password}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + string response = check self.clientEp->get(resourcePath); + return response; + } + # Logs out current logged in user session + # + # + return - successful operation + remote isolated function logoutUser() returns http:Response|error { + string resourcePath = string `/user/logout`; + http:Response response = check self.clientEp->get(resourcePath); + return response; + } + # Get user by user name + # + # + username - The name that needs to be fetched. Use user1 for testing. + # + return - successful operation + remote isolated function getUserByName(string username) returns User|error { + string resourcePath = string `/user/${getEncodedUri(username)}`; + User response = check self.clientEp->get(resourcePath); + return response; + } + # Updated user + # + # + username - name that need to be updated + # + request - Updated user object + # + return - Invalid user supplied + remote isolated function updateUser(string username, http:Request request) returns http:Response|error { + string resourcePath = string `/user/${getEncodedUri(username)}`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->put(resourcePath, request); + return response; + } + # Delete user + # + # + username - The name that needs to be deleted + # + return - Invalid username supplied + remote isolated function deleteUser(string username) returns http:Response|error { + string resourcePath = string `/user/${getEncodedUri(username)}`; + http:Response response = check self.clientEp-> delete(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_schema.bal b/openapi-cli/src/test/resources/expected_gen/petstore_schema.bal index df1f8e2cf..d835819c6 100644 --- a/openapi-cli/src/test/resources/expected_gen/petstore_schema.bal +++ b/openapi-cli/src/test/resources/expected_gen/petstore_schema.bal @@ -1,3 +1,64 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + public type Pets Pet[]; public type Error record { diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_schema_type.bal b/openapi-cli/src/test/resources/expected_gen/petstore_schema_type.bal index de3a1f6e0..d5c0d107b 100644 --- a/openapi-cli/src/test/resources/expected_gen/petstore_schema_type.bal +++ b/openapi-cli/src/test/resources/expected_gen/petstore_schema_type.bal @@ -1,3 +1,64 @@ +// AUTO-GENERATED FILE. +// This file is auto-generated by the Ballerina OpenAPI tool. + +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + public type PetArr Pet[]; public type Pet record { diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_schema_with_license.bal b/openapi-cli/src/test/resources/expected_gen/petstore_schema_with_license.bal index cb26450eb..9a4a6e293 100644 --- a/openapi-cli/src/test/resources/expected_gen/petstore_schema_with_license.bal +++ b/openapi-cli/src/test/resources/expected_gen/petstore_schema_with_license.bal @@ -1,5 +1,63 @@ // Copyright (c) 2021 All Rights Reserved. +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + public type Pets Pet[]; public type Error record { diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_service_swagger.bal b/openapi-cli/src/test/resources/expected_gen/petstore_service_swagger.bal new file mode 100644 index 000000000..255d26a5a --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/petstore_service_swagger.bal @@ -0,0 +1,157 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore.swagger.io"}); + +service /v2 on ep0 { + # Update an existing pet + # + # + payload - Pet object that needs to be added to the store + # + return - returns can be any of following types + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Pet not found) + # http:MethodNotAllowed (Validation exception) + resource function put pet(@http:Payload xml|Pet payload) returns http:BadRequest|http:NotFound|http:MethodNotAllowed { + } + # Add a new pet to the store + # + # + payload - Pet object that needs to be added to the store + # + return - Invalid input + resource function post pet(@http:Payload xml|Pet payload) returns http:MethodNotAllowed { + } + # Finds Pets by status + # + # + status - Status values that need to be considered for filter + # + return - returns can be any of following types + # Pet[] (successful operation) + # http:BadRequest (Invalid status value) + resource function get pet/findByStatus(("available"|"pending"|"sold")[] status) returns Pet[]|http:BadRequest { + } + # Finds Pets by tags + # + # + tags - Tags to filter by + # + return - returns can be any of following types + # Pet[] (successful operation) + # http:BadRequest (Invalid tag value) + resource function get pet/findByTags(string[] tags) returns Pet[]|http:BadRequest { + } + # Find pet by ID + # + # + petId - ID of pet to return + # + return - returns can be any of following types + # Pet (successful operation) + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Pet not found) + resource function get pet/[int petId]() returns Pet|http:BadRequest|http:NotFound { + } + # Updates a pet in the store with form data + # + # + petId - ID of pet that needs to be updated + # + payload - parameter description + # + return - Invalid input + resource function post pet/[int petId](@http:Payload map payload) returns http:MethodNotAllowed { + } + # Deletes a pet + # + # + petId - Pet id to delete + # + api_key - parameter description + # + return - returns can be any of following types + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Pet not found) + resource function delete pet/[int petId](@http:Header string? api_key) returns http:BadRequest|http:NotFound { + } + # uploads an image + # + # + petId - ID of pet to update + # + request - parameter description + # + return - successful operation + resource function post pet/[int petId]/uploadImage(http:Request request) returns OkApiResponse { + } + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory() returns StoreInventoryResponse { + } + # Place an order for a pet + # + # + request - order placed for purchasing the pet + # + return - returns can be any of following types + # OkOrder (successful operation) + # http:BadRequest (Invalid Order) + resource function post store/'order(http:Request request) returns OkOrder|http:BadRequest { + } + # Find purchase order by ID + # + # + orderId - ID of pet that needs to be fetched + # + return - returns can be any of following types + # Order (successful operation) + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Order not found) + resource function get store/'order/[int orderId]() returns Order|http:BadRequest|http:NotFound { + } + # Delete purchase order by ID + # + # + orderId - ID of the order that needs to be deleted + # + return - returns can be any of following types + # http:BadRequest (Invalid ID supplied) + # http:NotFound (Order not found) + resource function delete store/'order/[int orderId]() returns http:BadRequest|http:NotFound { + } + # Create user + # + # + request - Created user object + # + return - successful operation + resource function post user(http:Request request) returns http:Response { + } + # Creates list of users with given input array + # + # + request - List of user object + # + return - successful operation + resource function post user/createWithArray(http:Request request) returns http:Response { + } + # Creates list of users with given input array + # + # + request - List of user object + # + return - successful operation + resource function post user/createWithList(http:Request request) returns http:Response { + } + # Logs user into the system + # + # + username - The user name for login + # + password - The password for login in clear text + # + return - returns can be any of following types + # string (successful operation) + # http:BadRequest (Invalid username/password supplied) + resource function get user/login(string username, string password) returns string|http:BadRequest { + } + # Logs out current logged in user session + # + # + return - successful operation + resource function get user/logout() returns http:Response { + } + # Get user by user name + # + # + username - The name that needs to be fetched. Use user1 for testing. + # + return - returns can be any of following types + # User (successful operation) + # http:BadRequest (Invalid username supplied) + # http:NotFound (User not found) + resource function get user/[string username]() returns User|http:BadRequest|http:NotFound { + } + # Updated user + # + # + username - name that need to be updated + # + request - Updated user object + # + return - returns can be any of following types + # http:BadRequest (Invalid user supplied) + # http:NotFound (User not found) + resource function put user/[string username](http:Request request) returns http:BadRequest|http:NotFound { + } + # Delete user + # + # + username - The name that needs to be deleted + # + return - returns can be any of following types + # http:BadRequest (Invalid username supplied) + # http:NotFound (User not found) + resource function delete user/[string username]() returns http:BadRequest|http:NotFound { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_service.bal b/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_service.bal new file mode 100644 index 000000000..d5a9cf7de --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_service.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Create a pet + # + # + request - Request to add a pet + # + return - Successful operation + resource function post pets/my(http:Request request) returns OkAnydata { + } +} diff --git a/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_types.bal b/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_types.bal new file mode 100644 index 000000000..4a0883c4a --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/petstore_wildcard_types.bal @@ -0,0 +1,25 @@ +import ballerina/http; + +public type OkAnydata record {| + *http:Ok; + anydata body; +|}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/expected_gen/same_status_code.yaml b/openapi-cli/src/test/resources/expected_gen/same_status_code.yaml new file mode 100644 index 000000000..313db5a3b --- /dev/null +++ b/openapi-cli/src/test/resources/expected_gen/same_status_code.yaml @@ -0,0 +1,52 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /testPath: + get: + operationId: getTestpath + responses: + "200": + description: Ok + content: + application/json: + schema: + oneOf: + - type: boolean + - type: integer + format: int64 + - $ref: '#/components/schemas/Pet' + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + text/plain: + schema: + type: string +components: + schemas: + Pet: + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string diff --git a/openapi-cli/src/test/resources/expected_gen/x_init_description.bal b/openapi-cli/src/test/resources/expected_gen/x_init_description.bal index 98cbb0ab3..34fd6ca73 100644 --- a/openapi-cli/src/test/resources/expected_gen/x_init_description.bal +++ b/openapi-cli/src/test/resources/expected_gen/x_init_description.bal @@ -11,20 +11,42 @@ public isolated client class Client { # Log into NYTimes Developer Portal by visiting https://developer.nytimes.com/accounts/login. # Register an app and obtain the API Key following the process summarized [here](https://developer.nytimes.com/get-started). # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.nytimes.com/svc/movies/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://api.nytimes.com/svc/movies/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Get movie reviews that are critics' picks. You can either specify the reviewer name or use "all", "full-time", or "part-time". # # + return - An array of Movie Critics - remote isolated function criticsPicks() returns InlineResponse200|error { + remote isolated function criticsPicks() returns Inline_response_200|error { string resourcePath = string `/`; - InlineResponse200 response = check self.clientEp-> get(resourcePath); + Inline_response_200 response = check self.clientEp->get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_http_version.yaml b/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_http_version.yaml new file mode 100644 index 000000000..fa07ffdd8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_http_version.yaml @@ -0,0 +1,166 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT + x-ballerina-display: + label: COVID-19 + iconPath: "icon.png" + x-ballerina-init-description: | + The connector initialization doesn't require setting the API credentials. +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 +x-ballerina-http-configurations: + httpVersion: "1.1" +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/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_invalid_http_version.yaml b/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_invalid_http_version.yaml new file mode 100644 index 000000000..7912efb52 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/auth/scenarios/http_config_extension/petstore_with_invalid_http_version.yaml @@ -0,0 +1,166 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT + x-ballerina-display: + label: COVID-19 + iconPath: "icon.png" + x-ballerina-init-description: | + The connector initialization doesn't require setting the API credentials. +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 +x-ballerina-http-configurations: + httpVersion: "2.1" +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/openapi-cli/src/test/resources/generators/client/ballerina/any_types_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/any_types_payload.bal index 04064ce93..6fbb717b3 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/any_types_payload.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/any_types_payload.bal @@ -4,23 +4,43 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Create a pet # # + return - Null response - remote isolated function createPet(byte[] payload) returns http:Response|error { + remote isolated function createPet(http:Request request) returns http:Response|error { string resourcePath = string `/pets`; - http:Request request = new; - request.setPayload(payload); + // TODO: Update the request as needed; http:Response response = check self.clientEp->post(resourcePath, request); return response; } } - diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/binary_format_octet_stream_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/binary_format_octet_stream_payload.bal index 149bd3a45..a031855a3 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/binary_format_octet_stream_payload.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/binary_format_octet_stream_payload.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/byte_format_octet_stream_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/byte_format_octet_stream_payload.bal index 98cbe5224..1dc138725 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/byte_format_octet_stream_payload.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/byte_format_octet_stream_payload.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/client_template.bal b/openapi-cli/src/test/resources/generators/client/ballerina/client_template.bal index fa24b6fb5..de0787a9b 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/client_template.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/client_template.bal @@ -6,12 +6,34 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error?{ - http:Client httpEp = check new (serviceUrl, clientConfig); + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/combination_of_apikey_and_http_oauth.bal b/openapi-cli/src/test/resources/generators/client/ballerina/combination_of_apikey_and_http_oauth.bal index 430347d8d..0505c5cb8 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/combination_of_apikey_and_http_oauth.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/combination_of_apikey_and_http_oauth.bal @@ -1,50 +1,43 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # Represents API Key `api-key` - string apiKey; - # Represents API Key `api-key-2` - string apiKey2; -|}; - -# Provides Auth configurations needed when communicating with a remote HTTP endpoint. -public type AuthConfig record {| - # Auth Configuration - OAuth2ClientCredentialsGrantConfig|http:BearerTokenConfig|OAuth2RefreshTokenGrantConfig|ApiKeysConfig auth; -|}; - -# OAuth2 Client Credentials Grant Configs -public type OAuth2ClientCredentialsGrantConfig record {| - *http:OAuth2ClientCredentialsGrantConfig; - # Token URL - string tokenUrl = "https://dev.to/oauth/token"; -|}; - -# OAuth2 Refresh Token Grant Configs -public type OAuth2RefreshTokenGrantConfig record {| - *http:OAuth2RefreshTokenGrantConfig; - # Refresh URL - string refreshUrl = "https://dev.to/oauth/token"; -|}; - public isolated client class Client { final http:Client clientEp; final readonly & ApiKeysConfig? apiKeyConfig; # Gets invoked to initialize the `connector`. # - # + authConfig - Configurations used for Authentication - # + clientConfig - The configurations to be used when initializing 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(AuthConfig authConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - if authConfig.auth is ApiKeysConfig { - self.apiKeyConfig = (authConfig.auth).cloneReadOnly(); + public isolated function init(ConnectionConfig config, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + if config.auth is ApiKeysConfig { + self.apiKeyConfig = (config.auth).cloneReadOnly(); } else { - clientConfig.auth = authConfig.auth; + config.auth = config.auth; self.apiKeyConfig = (); } - http:Client httpEp = check new (serviceUrl, clientConfig); + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -80,7 +73,6 @@ public isolated client class Client { resourcePath = resourcePath + check getPathForQueryParam(queryParam); map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - //TODO: Update the request as needed; Pet response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/delete_with_header.bal b/openapi-cli/src/test/resources/generators/client/ballerina/delete_with_header.bal index a36a623ba..d4e8f30d4 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/delete_with_header.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/delete_with_header.bal @@ -4,28 +4,50 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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, http:ClientConfiguration clientConfig = {}) returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(string serviceUrl, ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Delete neither header nor request body. # - # + orderId - Order ID - # + riskId - Order Risk ID + # + order_id - Order ID + # + risk_id - Order Risk ID # + return - Status OK - remote isolated function deleteOrderRisk(string orderId, string riskId) returns http:Response|error { - string resourcePath = string `/admin/api/2021-10/orders/${getEncodedUri(orderId)}/risks/${getEncodedUri(riskId)}.json`; + remote isolated function delete_order_risk(string order_id, string risk_id) returns http:Response|error { + string resourcePath = string `/admin/api/2021-10/orders/${getEncodedUri(order_id)}/risks/${getEncodedUri(risk_id)}.json`; http:Response response = check self.clientEp-> delete(resourcePath); return response; } # Delete with request body. # # + return - Status OK - remote isolated function orderRisk(json payload) returns http:Response|error { + remote isolated function order_risk(json payload) returns http:Response|error { string resourcePath = string `/request-body`; http:Request request = new; request.setPayload(payload, "application/json"); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_functions.bal b/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_functions.bal index b8a588415..3654283d9 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_functions.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_functions.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -33,7 +55,6 @@ public isolated client class Client { remote isolated function createPet() returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_mix_params.bal b/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_mix_params.bal index ac15b8513..e70c641b9 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_mix_params.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/deprecated_mix_params.bal @@ -9,28 +9,50 @@ public isolated client class Client { # 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). # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api.soundcloud.com") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api.soundcloud.com") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Returns the comments posted on the track(track_id). # - # + trackId - SoundCloud Track id + # + track_id - SoundCloud Track id # + 'limit - Number of results to return in the collection. # + offset - Offset of first result. Deprecated, use `linked_partitioning` instead. - # + linkedPartitioning - Returns paginated collection of items (recommended, returning a list without pagination is deprecated and should not be used) + # + linked_partitioning - Returns paginated collection of items (recommended, returning a list without pagination is deprecated and should not be used) # # Deprecated parameters # + offset - # + return - Success - remote isolated function getCommentsOnTrack(int trackId, int 'limit = 50, @deprecated int offset = 0, boolean? linkedPartitioning = ()) returns InlineResponse200|error { - string resourcePath = string `/tracks/${getEncodedUri(trackId)}/comments`; - map queryParam = {"limit": 'limit, "offset": offset, "linked_partitioning": linkedPartitioning}; + remote isolated function getCommentsOnTrack(int track_id, int 'limit = 50, @deprecated int offset = 0, boolean? linked_partitioning = ()) returns Inline_response_200|error { + string resourcePath = string `/tracks/${getEncodedUri(track_id)}/comments`; + map queryParam = {"limit": 'limit, "offset": offset, "linked_partitioning": linked_partitioning}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - InlineResponse200 response = check self.clientEp->get(resourcePath); + Inline_response_200 response = check self.clientEp->get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/display_and_deprecated.bal b/openapi-cli/src/test/resources/generators/client/ballerina/display_and_deprecated.bal index d894e0bc1..1ca3ec447 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/display_and_deprecated.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/display_and_deprecated.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -34,7 +56,6 @@ public isolated client class Client { remote isolated function createPet() returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/header_integer_signed32.bal b/openapi-cli/src/test/resources/generators/client/ballerina/header_integer_signed32.bal new file mode 100644 index 000000000..a9825b7d9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/header_integer_signed32.bal @@ -0,0 +1,64 @@ +import ballerina/http; + + +public isolated client class Client { + final http:Client clientEp; + final readonly & ApiKeysConfig apiKeyConfig; + # Gets invoked to initialize the `connector`. + # + # + apiKeyConfig - API keys for authorization + # + 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(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://petstore.openapi.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); + return; + } + # Info for a specific pet + # + # + xRequestId - Tests header 01 + # + xRequestClient - Tests header 02 + # + xRequestPet - Tests header 03 + # + xRequestHeader - Tests header 04 + # + return - Expected response to a valid request + remote isolated function showPetById(int:Signed32 xRequestId, int:Signed32[] xRequestClient, Pet[] xRequestPet, int? xRequestHeader=()) returns http:Response|error { + string resourcePath = string `/pets`; + map headerValues = {"X-Request-ID": xRequestId, "X-Request-Client": xRequestClient, "X-Request-Pet": xRequestPet, "X-Request-Header": xRequestHeader, "X-API-KEY": self.apiKeyConfig.xApiKey}; + map httpHeaders = getMapForHeaders(headerValues); + http:Response response = check self.clientEp-> get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/header_optional.bal b/openapi-cli/src/test/resources/generators/client/ballerina/header_optional.bal index 1e3e9f282..185a5bf37 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/header_optional.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/header_optional.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/header_param_with_default_value.bal b/openapi-cli/src/test/resources/generators/client/ballerina/header_param_with_default_value.bal index 67c96a30c..8c7a4595f 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/header_param_with_default_value.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/header_param_with_default_value.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/header_parameter.bal b/openapi-cli/src/test/resources/generators/client/ballerina/header_parameter.bal index 5f1b5fbef..d9c0efeaf 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/header_parameter.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/header_parameter.bal @@ -1,9 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - string xApiKey; -|}; public isolated client class Client { final http:Client clientEp; @@ -11,11 +7,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.openapi.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://petstore.openapi.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/header_without_parameter.bal b/openapi-cli/src/test/resources/generators/client/ballerina/header_without_parameter.bal index 4867e6549..2b4450afb 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/header_without_parameter.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/header_without_parameter.bal @@ -1,21 +1,47 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - string xApiKey; -|}; - public isolated client class Client { final http:Client clientEp; final readonly & ApiKeysConfig apiKeyConfig; # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.openapi.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://petstore.openapi.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/integer_signed32_path_parameter.bal b/openapi-cli/src/test/resources/generators/client/ballerina/integer_signed32_path_parameter.bal new file mode 100644 index 000000000..abd33bdf9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/integer_signed32_path_parameter.bal @@ -0,0 +1,48 @@ +import ballerina/http; + + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # op1 + # + # + id - id value + # + payloadId - payload id value + # + return - Ok + remote isolated function operationId01(int:Signed32 id, int payloadId) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(id)}/payload/${getEncodedUri(payloadId)}`; + string response = check self.clientEp-> get(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/missing_server_url.bal b/openapi-cli/src/test/resources/generators/client/ballerina/missing_server_url.bal index 55b6f5d92..fd74cca05 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/missing_server_url.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/missing_server_url.bal @@ -7,11 +7,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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, http:ClientConfiguration clientConfig = {}) returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(string serviceUrl,ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/multipart_binary.bal b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_binary.bal new file mode 100644 index 000000000..24646afff --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_binary.bal @@ -0,0 +1,47 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Create a pet + # + # + request - Pet + # + return - Null response + remote isolated function createPet(http:Request request) returns http:Response|error { + string resourcePath = string `/pets`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata.bal b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata.bal index 4d7132516..49196f6fd 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -17,7 +39,7 @@ public isolated client class Client { # # + payload - Pet # + return - Null response - remote isolated function createPet(PetsBody payload) returns http:Response|error { + remote isolated function createPet(Pets_body payload) returns http:Response|error { string resourcePath = string `/pets`; http:Request request = new; mime:Entity[] bodyParts = check createBodyParts(payload); @@ -25,4 +47,17 @@ public isolated client class Client { http:Response response = check self.clientEp->post(resourcePath, request); return response; } + + # Create an user + # + # + payload - User + # + return - Null response + remote isolated function createUser(User_body payload) returns http:Response|error { + string resourcePath = string `/user`; + http:Request request = new; + mime:Entity[] bodyParts = check createBodyParts(payload); + request.setBodyParts(bodyParts); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata_empty.bal b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata_empty.bal new file mode 100644 index 000000000..24646afff --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/multipart_formdata_empty.bal @@ -0,0 +1,47 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Create a pet + # + # + request - Pet + # + return - Null response + remote isolated function createPet(http:Request request) returns http:Response|error { + string resourcePath = string `/pets`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/octet_stream_request_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/octet_stream_request_payload.bal new file mode 100644 index 000000000..0830f6025 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/octet_stream_request_payload.bal @@ -0,0 +1,59 @@ +import ballerina/http; + +# refComponent +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Creates a new user. + # + # + return - OK + resource isolated function post user(byte[] payload) returns http:Response|error { + string resourcePath = string `/user`; + http:Request request = new; + request.setPayload(payload, "application/octet-stream"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Creates a new payment. + # + # + payload - Details of the pet to be purchased + # + return - OK + resource isolated function post payment(byte[] payload) returns http:Response|error { + string resourcePath = string `/payment`; + http:Request request = new; + request.setPayload(payload, "application/octet-stream"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/openapi_display_annotation.bal b/openapi-cli/src/test/resources/generators/client/ballerina/openapi_display_annotation.bal index 780ac92a5..86bce0406 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/openapi_display_annotation.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/openapi_display_annotation.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. - string appid; -|}; - # 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. @display {label: "Current Weather Details", iconPath: "Path"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/operation_get.bal b/openapi-cli/src/test/resources/generators/client/ballerina/operation_get.bal index cd15ec897..752e622ac 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/operation_get.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/operation_get.bal @@ -6,11 +6,33 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://localhost:9090/petstore/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/operation_id.bal b/openapi-cli/src/test/resources/generators/client/ballerina/operation_id.bal index e25cb9936..210dafa8b 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/operation_id.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/operation_id.bal @@ -4,7 +4,7 @@ public isolated client class Client { public final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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 = "http://localhost:9090/petstore/v1", http:ClientConfiguration httpClientConfig = {}) returns error? { @@ -20,7 +20,7 @@ public isolated client class Client { remote isolated function createPet(Pet payload) returns http:Response | error { string resourcePath = string `/pet`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -33,7 +33,6 @@ public isolated client class Client { remote isolated function deletepetsBypetId(int petId) returns http:Response | error { string resourcePath = string `/pets/${getEncodedUri(petId)}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/operation_post.bal b/openapi-cli/src/test/resources/generators/client/ballerina/operation_post.bal index 91ffacb05..65d1ed1a2 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/operation_post.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/operation_post.bal @@ -5,18 +5,40 @@ public isolated client class Client { public final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://localhost:9090/petstore/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } remote isolated function pet(Pet payload) returns http:Response | error { string resourcePath = string `/pet`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_enum.bal b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_enum.bal new file mode 100644 index 000000000..a74faff91 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_enum.bal @@ -0,0 +1,67 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about +# Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! +# You can now help us improve the API whether it's by making changes to the definition itself or to the code. +# That way, with time, we can improve the API in general, and expose some of the new features in OAS3. +# +# _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ +# +# Some useful links: +# - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +# - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List meetings + # + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + group - Employee group + # + xDateFormat - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + xTimeZones - Time Zones of attendees + # + location - Meeting location + # + format - The response format you would like + # + return - HTTP Status Code:200. List of meetings returned. + remote isolated function listMeetings("Admin"|"HR"|"Engineering" group, ("IST"|"GMT"|"UTC")[] xTimeZones, "scheduled"|"live"|"upcoming" 'type = "live", ("available"|"pending")[]? status = (), "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? xDateFormat = (), RoomNo location = "R5", "json"|"jsonp"|"msgpack"|"html"? format = ()) returns MeetingList|error { + string resourcePath = string `/users/meetings/${getEncodedUri(group)}`; + map queryParam = {"type": 'type, "status": status, "location": location, "format": format}; + map queryParamEncoding = {"status": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + map headerValues = {"X-Date-Format": xDateFormat, "X-Time-Zones": xTimeZones}; + map httpHeaders = getMapForHeaders(headerValues); + MeetingList response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums.bal b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums.bal new file mode 100644 index 000000000..6ddf9ff67 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums.bal @@ -0,0 +1,65 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about +# Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! +# You can now help us improve the API whether it's by making changes to the definition itself or to the code. +# That way, with time, we can improve the API in general, and expose some of the new features in OAS3. +# +# _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ +# +# Some useful links: +# - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +# - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List meetings + # + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + xDateFormat - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + location - Meeting location + # + format - The response format you would like + # + return - HTTP Status Code:200. List of meetings returned. + remote isolated function listMeetings("scheduled"|"live"|"upcoming"? 'type = (), ("available"|"pending"?)[]? status = (), "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? xDateFormat = (), RoomNo location = "R5", "json"|"jsonp"|"msgpack"|"html"? format = ()) returns MeetingList|error { + string resourcePath = string `/users/meetings`; + map queryParam = {"type": 'type, "status": status, "location": location, "format": format}; + map queryParamEncoding = {"status": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + map headerValues = {"X-Date-Format": xDateFormat}; + map httpHeaders = getMapForHeaders(headerValues); + MeetingList response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums_resource.bal b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums_resource.bal new file mode 100644 index 000000000..1de93f685 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/parameters_with_nullable_enums_resource.bal @@ -0,0 +1,65 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about +# Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! +# You can now help us improve the API whether it's by making changes to the definition itself or to the code. +# That way, with time, we can improve the API in general, and expose some of the new features in OAS3. +# +# _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ +# +# Some useful links: +# - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +# - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List meetings + # + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + xDateFormat - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + location - Meeting location + # + format - The response format you would like + # + return - HTTP Status Code:200. List of meetings returned. + resource isolated function get users/meetings("scheduled"|"live"|"upcoming"? 'type = (), ("available"|"pending"?)[]? status = (), "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? xDateFormat = (), RoomNo location = "R5", "json"|"jsonp"|"msgpack"|"html"? format = ()) returns MeetingList|error { + string resourcePath = string `/users/meetings`; + map queryParam = {"type": 'type, "status": status, "location": location, "format": format}; + map queryParamEncoding = {"status": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + map headerValues = {"X-Date-Format": xDateFormat}; + map httpHeaders = getMapForHeaders(headerValues); + MeetingList response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/paramters_with_enum_resource.bal b/openapi-cli/src/test/resources/generators/client/ballerina/paramters_with_enum_resource.bal new file mode 100644 index 000000000..07792b0e9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/paramters_with_enum_resource.bal @@ -0,0 +1,67 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about +# Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! +# You can now help us improve the API whether it's by making changes to the definition itself or to the code. +# That way, with time, we can improve the API in general, and expose some of the new features in OAS3. +# +# _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ +# +# Some useful links: +# - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +# - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # List meetings + # + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + group - Employee group + # + xDateFormat - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + xTimeZones - Time Zones of attendees + # + location - Meeting location + # + format - The response format you would like + # + return - HTTP Status Code:200. List of meetings returned. + resource isolated function get users/meetings/["Admin"|"HR"|"Engineering" group](("IST"|"GMT"|"UTC")[] xTimeZones, "scheduled"|"live"|"upcoming" 'type = "live", ("available"|"pending")[]? status = (), "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? xDateFormat = (), RoomNo location = "R5", "json"|"jsonp"|"msgpack"|"html"? format = ()) returns MeetingList|error { + string resourcePath = string `/users/meetings/${getEncodedUri(group)}`; + map queryParam = {"type": 'type, "status": status, "location": location, "format": format}; + map queryParamEncoding = {"status": {style: FORM, explode: true}}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); + map headerValues = {"X-Date-Format": xDateFormat, "X-Time-Zones": xTimeZones}; + map httpHeaders = getMapForHeaders(headerValues); + MeetingList response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/path_param_duplicated_name.bal b/openapi-cli/src/test/resources/generators/client/ballerina/path_param_duplicated_name.bal index 6f2eed28d..cc6041b50 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/path_param_duplicated_name.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/path_param_duplicated_name.bal @@ -4,20 +4,42 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # - # + 'version - Version Id + # + version - Version Id # + versionName - Version Name # + return - Ok - remote isolated function operationId04(int 'version, string versionName) returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/version-name/${getEncodedUri(versionName)}`; + remote isolated function operationId04(int version, string versionName) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/version-name/${getEncodedUri(versionName)}`; string response = check self.clientEp-> get(resourcePath); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/path_param_with_ref_schema.bal b/openapi-cli/src/test/resources/generators/client/ballerina/path_param_with_ref_schema.bal index 3aaf7cce9..da6b8e814 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/path_param_with_ref_schema.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/path_param_with_ref_schema.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_valid.bal b/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_valid.bal index 3af2c77f0..c7dccabba 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_valid.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_valid.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -26,7 +48,6 @@ public isolated client class Client { remote isolated function operationId02() returns string|error { string resourcePath = string `/`; http:Request request = new; - //TODO: Update the request as needed; string response = check self.clientEp-> post(resourcePath, request); return response; } @@ -41,15 +62,15 @@ public isolated client class Client { } # # + return - Ok - remote isolated function operationId04(int 'version, string name) returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri(name)}`; + remote isolated function operationId04(int version, string name) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri(name)}`; string response = check self.clientEp-> get(resourcePath); return response; } # # + return - Ok - remote isolated function operationId05(int 'version, int 'limit) returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri('limit)}`; + remote isolated function operationId05(int version, int 'limit) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri('limit)}`; string response = check self.clientEp-> get(resourcePath); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_with_special_name.bal b/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_with_special_name.bal index db2455170..a0022f46a 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_with_special_name.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/path_parameter_with_special_name.bal @@ -4,20 +4,42 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # - # + 'version - Version Id + # + version - Version Id # + versionName - Version Name # + return - Ok - remote isolated function operationId04(int 'version, string versionName) returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri(versionName)}`; + remote isolated function operationId04(int version, string versionName) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri(versionName)}`; string response = check self.clientEp-> get(resourcePath); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_default_value.bal b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_default_value.bal index acd8f5acc..ce4db18bd 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_default_value.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_default_value.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_integer_value.bal b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_integer_value.bal new file mode 100644 index 000000000..44d681c4f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_integer_value.bal @@ -0,0 +1,66 @@ +import ballerina/http; + +# Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. +@display {label: "Open Weather Client"} +public isolated client class Client { + final http:Client clientEp; + final readonly & ApiKeysConfig apiKeyConfig; + # Gets invoked to initialize the `connector`. + # + # + apiKeyConfig - API keys for authorization + # + 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(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); + return; + } + # Provide weather forecast for any geographical coordinates + # + # + lat - Latitude + # + lon - Longtitude + # + exclude - test + # + units - units + # + return - Successful response + @display {label: "Weather Forecast"} + remote isolated function getWeatherForecast(@display {label: "Latitude"} int:Signed32 lat, @display {label:"Units"} int units, @display {label:"Longtitude"} int:Signed32? lon=(), @display {label:"Exclude"} int exclude=100) returns WeatherForecast|error { + string resourcePath = string `/onecall`; + map queryParam = {"lat": lat, "lon": lon, "exclude": exclude, "units": units, "appid": self.apiKeyConfig.appid}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + WeatherForecast response = check self.clientEp-> get(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_ref_schema.bal b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_ref_schema.bal index 6a16a777c..c1c4fbf86 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_ref_schema.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_with_ref_schema.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_without_default_value.bal b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_without_default_value.bal index aea5bc9eb..25955bd7c 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/query_param_without_default_value.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/query_param_without_default_value.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/queryparam_encoding_map_gen.bal b/openapi-cli/src/test/resources/generators/client/ballerina/queryparam_encoding_map_gen.bal index cd77db107..c336079b8 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/queryparam_encoding_map_gen.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/queryparam_encoding_map_gen.bal @@ -4,24 +4,46 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api.stripe.com/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api.stripe.com/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } #

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.

# - # + collectionMethod - The collection method of the invoice to retrieve. Either `charge_automatically` or `send_invoice`. + # + collection_method - The collection method of the invoice to retrieve. Either `charge_automatically` or `send_invoice`. # + created - 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 - # + dueDate - 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 + # + due_date - 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 # + subscriptions - Only return invoices for the subscription specified by this subscription ID. # + return - Response - remote isolated function listInvoices(string? collectionMethod = (), Created? created = (), DueDate? dueDate = (), string[]? subscriptions = ()) returns json|error { + remote isolated function listInvoices("charge_automatically"|"send_invoice"? collection_method = (), Created? created = (), Due_date? due_date = (), string[]? subscriptions = ()) returns json|error { string resourcePath = string `/v1/invoices`; - map queryParam = {"collection_method": collectionMethod, "created": created, "due_date": dueDate, "subscriptions": subscriptions}; + map queryParam = {"collection_method": collection_method, "created": created, "due_date": due_date, "subscriptions": subscriptions}; map queryParamEncoding = {"created": {style: DEEPOBJECT, explode: true}, "due_date": {style: DEEPOBJECT, explode: true}, "subscriptions": {style: FORM, explode: true}}; resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding); json response = check self.clientEp->get(resourcePath); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_allOf_scenarios.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_allOf_scenarios.bal index cb5d62a63..3df7b9a04 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_allOf_scenarios.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_allOf_scenarios.bal @@ -6,21 +6,43 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new(serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Request Body has allOf with specific properties. # # + return - OK - remote isolated function updateXMLUser(Path01Body payload) returns http:Response|error { + remote isolated function updateXMLUser(Path01_body payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->put(resourcePath, request); @@ -29,10 +51,10 @@ public isolated client class Client { # Request Body has nested allOf. # # + return - OK - remote isolated function postXMLUser(Path01Body1 payload) returns http:Response|error { + remote isolated function postXMLUser(Path01_body_1 payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -43,7 +65,7 @@ public isolated client class Client { remote isolated function postXMLUserInLineArray(CompoundArrayItemPostXMLUserInLineArrayRequest payload) returns http:Response|error { string resourcePath = string `/path02`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_array.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_array.bal index 600cce711..3951ac38c 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_array.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_array.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -19,7 +41,7 @@ public isolated client class Client { remote isolated function updateUser(string[] payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_basic_scenarios.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_basic_scenarios.bal index dca20a5eb..d7a989b48 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_basic_scenarios.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_basic_scenarios.bal @@ -6,21 +6,43 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # 02 Example for rb has inline requestbody. # # + return - OK - remote isolated function updateUser(Path01Body payload) returns http:Response|error { + remote isolated function updateUser(Path01_body payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; @@ -31,7 +53,7 @@ public isolated client class Client { remote isolated function postUser(User payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -43,7 +65,7 @@ public isolated client class Client { remote isolated function updateNewUser(User payload) returns http:Response|error { string resourcePath = string `/path02`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; @@ -54,7 +76,7 @@ public isolated client class Client { remote isolated function postNewUser(User[] payload) returns http:Response|error { string resourcePath = string `/path02`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -62,10 +84,10 @@ public isolated client class Client { # 06 Example for rb has array inline requestbody. # # + return - OK - remote isolated function updateXMLUser(Path03Body payload) returns http:Response|error { + remote isolated function updateXMLUser(Path03_body payload) returns http:Response|error { string resourcePath = string `/path03`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->put(resourcePath, request); @@ -74,10 +96,10 @@ public isolated client class Client { # 05 Example for rb has array inline requestbody. # # + return - OK - remote isolated function postXMLUser(Path03Body1 payload) returns http:Response|error { + remote isolated function postXMLUser(Path03_body_1 payload) returns http:Response|error { string resourcePath = string `/path03`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); @@ -86,10 +108,10 @@ public isolated client class Client { # 07 Example for rb has array inline requestbody. # # + return - OK - remote isolated function postXMLUserInLineArray(Path04Body[] payload) returns http:Response|error { + remote isolated function postXMLUserInLineArray(Path04_body[] payload) returns http:Response|error { string resourcePath = string `/path04`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_empty_array.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_empty_array.bal index ba7e28ffa..bb3a3cf3c 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_empty_array.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_empty_array.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -19,7 +41,7 @@ public isolated client class Client { remote isolated function updateUser(json[] payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_has_object_content_without_property.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_has_object_content_without_property.bal new file mode 100644 index 000000000..3d94782b5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_has_object_content_without_property.bal @@ -0,0 +1,104 @@ +import ballerina/http; +import ballerina/xmldata; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://localhost:9090/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Request body has object schema content without the properties field + # + # + payload - A JSON object containing pet information + # + return - Ok + resource isolated function put greeting(record{} payload) returns Person|error { + string resourcePath = string `/greeting`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + Person response = check self.clientEp->put(resourcePath, request); + return response; + } + # The Request body is with reference to the reusable requestBody with content type has object without properties + # + # + return - Ok + resource isolated function post greeting(record{} payload) returns string|error { + string resourcePath = string `/greeting`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + string response = check self.clientEp->post(resourcePath, request); + return response; + } + # RequestBody has object content without properties with vendor-specific media type vnd.petstore.v3.diff+json + # + # + return - Ok + resource isolated function put greeting02(record{} payload) returns string|error { + string resourcePath = string `/greeting02`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/vnd.petstore.v3.diff+json"); + string response = check self.clientEp->put(resourcePath, request); + return response; + } + # RequestBody has object content without properties with application/xml + # + # + return - Ok + resource isolated function post greeting02(record{} payload) returns string|error { + string resourcePath = string `/greeting02`; + http:Request request = new; + json jsonBody = payload.toJson(); + xml? xmlBody = check xmldata:fromJson(jsonBody); + request.setPayload(xmlBody, "application/xml"); + string response = check self.clientEp->post(resourcePath, request); + return response; + } + # Request body has properties with {} value + # + # + return - Ok + resource isolated function put greeting03(record{} payload) returns http:Response|error { + string resourcePath = string `/greeting03`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + http:Response response = check self.clientEp->put(resourcePath, request); + return response; + } + # Request body has non-standard media type application/zip with object content without properties + # + # + return - Ok + resource isolated function post greeting03(http:Request request) returns http:Response|error { + string resourcePath = string `/greeting03`; + // TODO: Update the request as needed; + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_oneOf_scenarios.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_oneOf_scenarios.bal index 9df07adbc..1f313c5ed 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_oneOf_scenarios.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_oneOf_scenarios.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -17,10 +39,10 @@ public isolated client class Client { # # + payload - A JSON object containing pet information # + return - OK - remote isolated function postXMLUser(Path01Body payload) returns http:Response|error { + remote isolated function postXMLUser(Path01_body payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_with_ref.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_with_ref.bal new file mode 100644 index 000000000..d1a5baef7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_with_ref.bal @@ -0,0 +1,61 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Create a pet + # + # + payload - Return from creating a pet + # + return - Successful operation + remote isolated function createPet(CreatedPet_RequestBody payload) returns http:Response|error { + string resourcePath = string `/pets`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } + # Create a pet + # + # + payload - Return from creating a pet + # + return - Successful operation + remote isolated function createMyPet(Pet payload) returns http:Response|error { + string resourcePath = string `/my/pets`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/json"); + http:Response response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_without_schema.bal b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_without_schema.bal index d524c7ee1..a37a68d5d 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/request_body_without_schema.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/request_body_without_schema.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/union_path_parameter.bal b/openapi-cli/src/test/resources/generators/client/ballerina/union_path_parameter.bal new file mode 100644 index 000000000..e7353bb99 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/union_path_parameter.bal @@ -0,0 +1,54 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # + # + id - id anyOf + # + return - Ok + resource isolated function get v1/[Id id]() returns string|error { + string resourcePath = string `/v1/${getEncodedUri(id)}`; + string response = check self.clientEp->get(resourcePath); + return response; + } + # + # + id - id oneOf + # + return - Ok + resource isolated function post v1/[Id_1 id]() returns string|error { + string resourcePath = string `/v1/${getEncodedUri(id)}`; + http:Request request = new; + string response = check self.clientEp-> post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/union_path_types.bal b/openapi-cli/src/test/resources/generators/client/ballerina/union_path_types.bal new file mode 100644 index 000000000..ddcfa77fe --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/union_path_types.bal @@ -0,0 +1,3 @@ +public type Id int|string; + +public type Id_1 int|string; diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_request_body.bal b/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_request_body.bal new file mode 100644 index 000000000..421bd9a46 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_request_body.bal @@ -0,0 +1,49 @@ +import ballerina/http; + +# The Stripe REST API. Please see https://stripe.com/docs/api for more details. +public isolated client class Client { + final http:Client clientEp; + # 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, ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + #

Creates a new customer object.

+ # + # + customer - Customer ID + # + request - Customer Details + # + return - Successful response. + remote isolated function postCustomers(string customer, http:Request request) returns Customer|error { + string resourcePath = string `/v1/customer/${getEncodedUri(customer)}`; + // TODO: Update the request as needed; + Customer response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_text_media_type.bal b/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_text_media_type.bal new file mode 100644 index 000000000..60805223a --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/unsupported_text_media_type.bal @@ -0,0 +1,47 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Create a pet + # + # + return - Response of create pet + remote isolated function createPet(string payload) returns string|error { + string resourcePath = string `/pets`; + http:Request request = new; + request.setPayload(payload, "text/xxx"); + string response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/url_encoded_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/url_encoded_payload.bal index 6c0c48d8c..21ffafe01 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/url_encoded_payload.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/url_encoded_payload.bal @@ -5,20 +5,42 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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, http:ClientConfiguration clientConfig = {}) returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(string serviceUrl,ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } #

Retrieves a PaymentMethod object.

# - # + paymentMethod - Payment Method + # + payment_method - Payment Method # + return - Successful response. - remote isolated function getPaymentMethodsPaymentMethod(string paymentMethod) returns json|error { - string resourcePath = string `/v1/payment_methods/${getEncodedUri(paymentMethod)}`; + remote isolated function getPaymentMethodsPaymentMethod(string payment_method) returns json|error { + string resourcePath = string `/v1/payment_methods/${getEncodedUri(payment_method)}`; json response = check self.clientEp->get(resourcePath); return response; } @@ -27,7 +49,7 @@ public isolated client class Client { # + customer - Customer ID # + payload - Customer Details # + return - Successful response. - remote isolated function postCustomers(string customer, CustomerCustomerBody payload) returns Customer|error { + remote isolated function postCustomers(string customer, Customer_customer_body payload) returns Customer|error { string resourcePath = string `/v1/customer/${getEncodedUri(customer)}`; http:Request request = new; string encodedRequestBody = createFormURLEncodedRequestBody(payload); diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_payload.bal b/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_payload.bal index 1826ea863..6fbb717b3 100644 --- a/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_payload.bal +++ b/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_payload.bal @@ -4,21 +4,42 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # Create a pet # # + return - Null response - remote isolated function createPet(byte[] payload) returns http:Response|error { + remote isolated function createPet(http:Request request) returns http:Response|error { string resourcePath = string `/pets`; - http:Request request = new; - request.setPayload(payload, "application/vnd.ms-excel"); + // TODO: Update the request as needed; http:Response response = check self.clientEp->post(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_with_subtype.bal b/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_with_subtype.bal new file mode 100644 index 000000000..a50f9ed0e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/ballerina/vendor_specific_with_subtype.bal @@ -0,0 +1,61 @@ +import ballerina/http; +import ballerina/xmldata; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://petstore.{host}.io/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Create a pet + # + # + return - List of existing pets + remote isolated function createPet(Pet payload) returns Pets|error { + string resourcePath = string `/pets`; + http:Request request = new; + json jsonBody = payload.toJson(); + request.setPayload(jsonBody, "application/vnd.petstore.v3.diff+json"); + Pets response = check self.clientEp->post(resourcePath, request); + return response; + } + # Create a pet + # + # + return - List of existing pets + remote isolated function createPetV0(Pet payload) returns Pets|error { + string resourcePath = string `/v0/pets`; + http:Request request = new; + json jsonBody = payload.toJson(); + xml? xmlBody = check xmldata:fromJson(jsonBody); + request.setPayload(xmlBody, "application/vnd.petstore.v3.diff+xml"); + Pets response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/api2pdf.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/api2pdf.bal index 07cd3cca6..53094b3bc 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/api2pdf.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/api2pdf.bal @@ -1,13 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # Autherization header - string authorization; - # Api key query name - string apikey; -|}; - # Client endpoint for the given API public isolated client class Client { final http:Client clientEp; @@ -15,11 +7,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, string serviceUrl, http:ClientConfiguration clientConfig = {}) returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, string serviceUrl, ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; @@ -33,7 +56,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -59,7 +82,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -73,7 +96,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -87,7 +110,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -101,7 +124,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -127,7 +150,7 @@ public isolated client class Client { map headerValues = {"Authorization": self.apiKeyConfig.authorization}; map httpHeaders = getMapForHeaders(headerValues); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApiResponseSuccess response = check self.clientEp->post(resourcePath, request, httpHeaders); return response; @@ -140,11 +163,11 @@ public isolated client class Client { # + height - Height of the barcode generated image # + width - Width of the barcode generated image # + return - An image of the generated barcode or QR code - remote isolated function zebraGET(string format, string value, boolean? showlabel = (), int? height = (), int? width = ()) returns string|error { + remote isolated function zebraGET(string format, string value, boolean? showlabel = (), int? height = (), int? width = ()) returns byte[]|error { string resourcePath = string `/zebra`; map queryParam = {"format": format, "value": value, "showlabel": showlabel, "height": height, "width": width, "apikey": self.apiKeyConfig.apikey}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - string response = check self.clientEp-> get(resourcePath); + byte[] response = check self.clientEp-> get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/bitbucket.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/bitbucket.bal index 5796887bb..565fdd805 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/bitbucket.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/bitbucket.bal @@ -16,7 +16,7 @@ public type PriceEstimateArr PriceEstimate[]; public isolated client class Client { final http:Client clientEp; final readonly & map apiKeys; - public isolated function init(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api.uber.com/v1") returns error? { + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "https://api.uber.com/v1") returns error? { http:Client httpEp = check new (serviceUrl, clientConfig); self.clientEp = httpEp; self.apiKeys = apiKeyConfig.apiKeys.cloneReadOnly(); diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/covid19_openapi.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/covid19_openapi.bal index cd6627e1b..69eaddd6a 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/covid19_openapi.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/covid19_openapi.bal @@ -9,11 +9,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/description_with_special_characters.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/description_with_special_characters.bal new file mode 100644 index 000000000..eb5c0c21f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/description_with_special_characters.bal @@ -0,0 +1,58 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Add a new pet to the store + # + # + autoUnicode - Specifies how to deal with message text that contains characters not present in the GSM 03.38 character set. + # Messages that contain only GSM 03.38 characters are not affected by this setting. + # If the value is `true` then a message containing non-GSM 03.38 characters will be transmitted as a Unicode SMS (which is most likely more costly). + # Please note: when `auto-unicode` is `true` and the value of the `encoding` property is specified as `UNICODE`, the message will always be sent as `UNICODE`. + # If the value is `false` and the `encoding` property is `TEXT` then non-GSM 03.38 characters will be replaced by the `?` character. + # When using this setting on the API, you should take case to ensure that your message is _clean_. + # Invisible unicode and unexpected characters could unintentionally convert an message to `UNICODE`. A common mistake is to use the backtick character (\`) which is unicode and will turn your`TEXT` message into a `UNICODE` message. + # + payload - Create a new pet in the store + # + return - Successful operation + remote isolated function addPet(json payload, boolean autoUnicode = false) returns json|error { + string resourcePath = string `/pet`; + map queryParam = {"auto-unicode": autoUnicode}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + http:Request request = new; + request.setPayload(payload, "application/json"); + json response = check self.clientEp->post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/display_annotation.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/display_annotation.bal index f59a2383a..c769a5ccd 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/display_annotation.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/display_annotation.bal @@ -6,11 +6,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -21,7 +43,7 @@ public isolated client class Client { remote isolated function updatePet(Pet payload) returns http:Response|error { string resourcePath = string `/pet`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/duplicated_response.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/duplicated_response.bal index 4f1c28b4c..7f85045fe 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/duplicated_response.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/duplicated_response.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_0.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_0.bal new file mode 100644 index 000000000..2bf163edf --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_0.bal @@ -0,0 +1,59 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://app.launchdarkly.com/api/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # + # + return - Feature flag approval request response + remote isolated function op1() returns StringObject|error { + string resourcePath = string `/projects`; + StringObject response = check self.clientEp->get(resourcePath); + return response; + } + # + # + return - Feature flag approval request response + remote isolated function op2() returns IntegerObject|error { + string resourcePath = string `/projects`; + http:Request request = new; + IntegerObject response = check self.clientEp-> post(resourcePath, request); + return response; + } + # + # + return - Feature flag approval request response + remote isolated function op3() returns NumberObject|error { + string resourcePath = string `/projects`; + NumberObject response = check self.clientEp-> delete(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_1.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_1.bal new file mode 100644 index 000000000..2bf163edf --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/format_types_v3_1.bal @@ -0,0 +1,59 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://app.launchdarkly.com/api/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # + # + return - Feature flag approval request response + remote isolated function op1() returns StringObject|error { + string resourcePath = string `/projects`; + StringObject response = check self.clientEp->get(resourcePath); + return response; + } + # + # + return - Feature flag approval request response + remote isolated function op2() returns IntegerObject|error { + string resourcePath = string `/projects`; + http:Request request = new; + IntegerObject response = check self.clientEp-> post(resourcePath, request); + return response; + } + # + # + return - Feature flag approval request response + remote isolated function op3() returns NumberObject|error { + string resourcePath = string `/projects`; + NumberObject response = check self.clientEp-> delete(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/header_with_enum.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/header_with_enum.bal new file mode 100644 index 000000000..a62aca8ef --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/header_with_enum.bal @@ -0,0 +1,48 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Returns pet inventories by status + # + # + return - successful operation + remote isolated function getInventory(("X"|"Y"|"Z")[]? xClient = ()) returns json|error { + string resourcePath = string `/store/inventory`; + map headerValues = {"X-CLIENT": xClient}; + map httpHeaders = getMapForHeaders(headerValues); + json response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/incorrect_format.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/incorrect_format.bal new file mode 100644 index 000000000..aabcf0084 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/incorrect_format.bal @@ -0,0 +1,57 @@ +import ballerina/http; + +# This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about +# Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! +# You can now help us improve the API whether it's by making changes to the definition itself or to the code. +# That way, with time, we can improve the API in general, and expose some of the new features in OAS3. +# +# Some useful links: +# - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +# - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "https://petstore3.swagger.io/api/v3") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # Finds Pets by status + # + # + status - Status values that need to be considered for filter + # + 'limit - The number of client accounts to return on each page of results. The default value is `50`. Entering a `limit` value less than the minimum (`10`) or greater than the maximum (`50`) is ignored and the system uses the default values. Depending on the `limit` you specify, the system determines the `offset` parameter to use (number of records to skip) and includes it in the link used to get the next page of results. + # + return - successful operation + remote isolated function findPetsByStatus("available"|"pending"|"sold" status = "available", string 'limit = "50") returns Pet[]|error { + string resourcePath = string `/pet/findByStatus`; + map queryParam = {"status": status, "limit": 'limit}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + Pet[] response = check self.clientEp->get(resourcePath); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/jira_openapi.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/jira_openapi.bal index c6bebd334..6893c843a 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/jira_openapi.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/jira_openapi.bal @@ -67,7 +67,7 @@ public isolated client class Client { remote isolated function updateCustomFieldValue(string fieldIdOrKey, CustomFieldValueUpdateRequest payload) returns json|error { string resourcePath = string `/rest/api/2/app/field/${fieldIdOrKey}/value`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -87,7 +87,7 @@ public isolated client class Client { remote isolated function setApplicationProperty(string id, SimpleApplicationPropertyBean payload) returns ApplicationProperty|error { string resourcePath = string `/rest/api/2/application-properties/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ApplicationProperty response = check self.clientEp->put(resourcePath, request); return response; @@ -115,7 +115,6 @@ public isolated client class Client { remote isolated function removeAttachment(string id) returns http:Response | error { string resourcePath = string `/rest/api/2/attachment/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -146,7 +145,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PageBeanComment response = check self.clientEp->post(resourcePath, request); return response; @@ -164,7 +163,7 @@ public isolated client class Client { remote isolated function setCommentProperty(string commentId, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/comment/${commentId}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -172,14 +171,13 @@ public isolated client class Client { remote isolated function deleteCommentProperty(string commentId, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/comment/${commentId}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function createComponent(Component payload) returns Component|error { string resourcePath = string `/rest/api/2/component`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Component response = check self.clientEp->post(resourcePath, request); return response; @@ -192,7 +190,7 @@ public isolated client class Client { remote isolated function updateComponent(string id, Component payload) returns Component|error { string resourcePath = string `/rest/api/2/component/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Component response = check self.clientEp->put(resourcePath, request); return response; @@ -202,7 +200,6 @@ public isolated client class Client { map queryParam = {moveIssuesTo: moveIssuesTo}; resourcePath = resourcePath + check check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -224,7 +221,7 @@ public isolated client class Client { remote isolated function selectTimeTrackingImplementation(TimeTrackingProvider payload) returns json|error { string resourcePath = string `/rest/api/2/configuration/timetracking`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -242,7 +239,7 @@ public isolated client class Client { remote isolated function setSharedTimeTrackingConfiguration(TimeTrackingConfiguration payload) returns TimeTrackingConfiguration|error { string resourcePath = string `/rest/api/2/configuration/timetracking/options`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); TimeTrackingConfiguration response = check self.clientEp->put(resourcePath, request); return response; @@ -257,7 +254,7 @@ public isolated client class Client { remote isolated function updateCustomFieldOptions(int fieldId, UpdateCustomFieldOption payload) returns json|error { string resourcePath = string `/rest/api/2/customField/${fieldId}/option`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -265,7 +262,7 @@ public isolated client class Client { remote isolated function createCustomFieldOptions(int fieldId, BulkCreateCustomFieldOptionRequest payload) returns json|error { string resourcePath = string `/rest/api/2/customField/${fieldId}/option`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -285,7 +282,7 @@ public isolated client class Client { remote isolated function createDashboard(DashboardDetails payload) returns Dashboard|error { string resourcePath = string `/rest/api/2/dashboard`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Dashboard response = check self.clientEp->post(resourcePath, request); return response; @@ -310,7 +307,7 @@ public isolated client class Client { remote isolated function setDashboardItemProperty(string dashboardId, string itemId, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/dashboard/${dashboardId}/items/${itemId}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -318,7 +315,6 @@ public isolated client class Client { remote isolated function deleteDashboardItemProperty(string dashboardId, string itemId, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/dashboard/${dashboardId}/items/${itemId}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -330,7 +326,7 @@ public isolated client class Client { remote isolated function updateDashboard(string id, DashboardDetails payload) returns Dashboard|error { string resourcePath = string `/rest/api/2/dashboard/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Dashboard response = check self.clientEp->put(resourcePath, request); return response; @@ -338,14 +334,13 @@ public isolated client class Client { remote isolated function deleteDashboard(string id) returns http:Response | error { string resourcePath = string `/rest/api/2/dashboard/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function copyDashboard(string id, DashboardDetails payload) returns Dashboard|error { string resourcePath = string `/rest/api/2/dashboard/${id}/copy`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Dashboard response = check self.clientEp->post(resourcePath, request); return response; @@ -355,7 +350,7 @@ public isolated client class Client { map queryParam = {'check: 'check}; resourcePath = resourcePath + check check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); JiraExpressionsAnalysis response = check self.clientEp->post(resourcePath, request); return response; @@ -365,7 +360,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); JiraExpressionResult response = check self.clientEp->post(resourcePath, request); return response; @@ -378,7 +373,7 @@ public isolated client class Client { remote isolated function createCustomField(CustomFieldDefinitionJsonBean payload) returns FieldDetails|error { string resourcePath = string `/rest/api/2/field`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); FieldDetails response = check self.clientEp->post(resourcePath, request); return response; @@ -393,7 +388,7 @@ public isolated client class Client { remote isolated function updateCustomField(string fieldId, UpdateCustomFieldDetails payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -408,7 +403,7 @@ public isolated client class Client { remote isolated function createCustomFieldContext(string fieldId, CreateCustomFieldContext payload) returns CreateCustomFieldContext|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); CreateCustomFieldContext response = check self.clientEp->post(resourcePath, request); return response; @@ -423,7 +418,7 @@ public isolated client class Client { remote isolated function setDefaultValues(string fieldId, CustomFieldContextDefaultValueUpdate payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/defaultValue`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -440,7 +435,7 @@ public isolated client class Client { map queryParam = {startAt: startAt, maxResults: maxResults}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PageBeanContextForProjectAndIssueType response = check self.clientEp->post(resourcePath, request); return response; @@ -455,7 +450,7 @@ public isolated client class Client { remote isolated function updateCustomFieldContext(string fieldId, int contextId, CustomFieldContextUpdateDetails payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -463,14 +458,13 @@ public isolated client class Client { remote isolated function deleteCustomFieldContext(string fieldId, int contextId) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } remote isolated function addIssueTypesToContext(string fieldId, int contextId, IssueTypeIds payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/issuetype`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -478,7 +472,7 @@ public isolated client class Client { remote isolated function removeIssueTypesFromContext(string fieldId, int contextId, IssueTypeIds payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/issuetype/remove`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -493,7 +487,7 @@ public isolated client class Client { remote isolated function updateCustomFieldOption(string fieldId, int contextId, BulkCustomFieldOptionUpdateRequest payload) returns CustomFieldUpdatedContextOptionsList|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/option`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); CustomFieldUpdatedContextOptionsList response = check self.clientEp->put(resourcePath, request); return response; @@ -501,7 +495,7 @@ public isolated client class Client { remote isolated function createCustomFieldOption(string fieldId, int contextId, BulkCustomFieldOptionCreateRequest payload) returns CustomFieldCreatedContextOptionsList|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/option`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); CustomFieldCreatedContextOptionsList response = check self.clientEp->post(resourcePath, request); return response; @@ -509,7 +503,7 @@ public isolated client class Client { remote isolated function reorderCustomFieldOptions(string fieldId, int contextId, OrderOfCustomFieldOptions payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/option/move`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -517,14 +511,13 @@ public isolated client class Client { remote isolated function deleteCustomFieldOption(string fieldId, int contextId, int optionId) returns http:Response | error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/option/${optionId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request); return response; } remote isolated function assignProjectsToCustomFieldContext(string fieldId, int contextId, ProjectIds payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -532,7 +525,7 @@ public isolated client class Client { remote isolated function removeCustomFieldContextFromProjects(string fieldId, int contextId, ProjectIds payload) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldId}/context/${contextId}/project/remove`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -561,7 +554,7 @@ public isolated client class Client { remote isolated function createIssueFieldOption(string fieldKey, IssueFieldOptionCreateBean payload) returns IssueFieldOption|error { string resourcePath = string `/rest/api/2/field/${fieldKey}/option`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueFieldOption response = check self.clientEp->post(resourcePath, request); return response; @@ -588,7 +581,7 @@ public isolated client class Client { remote isolated function updateIssueFieldOption(string fieldKey, int optionId, IssueFieldOption payload) returns IssueFieldOption|error { string resourcePath = string `/rest/api/2/field/${fieldKey}/option/${optionId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueFieldOption response = check self.clientEp->put(resourcePath, request); return response; @@ -596,7 +589,6 @@ public isolated client class Client { remote isolated function deleteIssueFieldOption(string fieldKey, int optionId) returns json|error { string resourcePath = string `/rest/api/2/field/${fieldKey}/option/${optionId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -605,7 +597,6 @@ public isolated client class Client { map queryParam = {replaceWith: replaceWith, jql: jql}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; TaskProgressBeanRemoveOptionFromIssuesResult response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -647,7 +638,7 @@ public isolated client class Client { remote isolated function assignFieldConfigurationSchemeToProject(FieldConfigurationSchemeProjectAssociation payload) returns json|error { string resourcePath = string `/rest/api/2/fieldconfigurationscheme/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -664,7 +655,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Filter response = check self.clientEp->post(resourcePath, request); return response; @@ -677,7 +668,7 @@ public isolated client class Client { remote isolated function setDefaultShareScope(DefaultShareScope payload) returns DefaultShareScope|error { string resourcePath = string `/rest/api/2/filter/defaultShareScope`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); DefaultShareScope response = check self.clientEp->put(resourcePath, request); return response; @@ -715,7 +706,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Filter response = check self.clientEp->put(resourcePath, request); return response; @@ -723,7 +714,6 @@ public isolated client class Client { remote isolated function deleteFilter(int id) returns http:Response | error { string resourcePath = string `/rest/api/2/filter/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -741,7 +731,6 @@ public isolated client class Client { remote isolated function resetColumns(int id) returns http:Response | error { string resourcePath = string `/rest/api/2/filter/${id}/columns`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -750,7 +739,6 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; Filter response = check self.clientEp-> put(resourcePath, request); return response; } @@ -759,7 +747,6 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; Filter response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -771,7 +758,7 @@ public isolated client class Client { remote isolated function addSharePermission(int id, SharePermissionInputBean payload) returns SharePermissionArr|error { string resourcePath = string `/rest/api/2/filter/${id}/permission`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); SharePermissionArr response = check self.clientEp->post(resourcePath, request); return response; @@ -784,7 +771,6 @@ public isolated client class Client { remote isolated function deleteSharePermission(int id, int permissionId) returns http:Response | error { string resourcePath = string `/rest/api/2/filter/${id}/permission/${permissionId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -798,7 +784,7 @@ public isolated client class Client { remote isolated function createGroup(AddGroupBean payload) returns Group|error { string resourcePath = string `/rest/api/2/group`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Group response = check self.clientEp->post(resourcePath, request); return response; @@ -808,7 +794,6 @@ public isolated client class Client { map queryParam = {groupname: groupname, swapGroup: swapGroup}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -831,7 +816,7 @@ public isolated client class Client { map queryParam = {groupname: groupname}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Group response = check self.clientEp->post(resourcePath, request); return response; @@ -841,7 +826,6 @@ public isolated client class Client { map queryParam = {groupname: groupname, username: username, accountId: accountId}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -869,7 +853,7 @@ public isolated client class Client { map queryParam = {updateHistory: updateHistory}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); CreatedIssue response = check self.clientEp->post(resourcePath, request); return response; @@ -877,7 +861,7 @@ public isolated client class Client { remote isolated function createIssues(IssuesUpdateBean payload) returns CreatedIssues|error { string resourcePath = string `/rest/api/2/issue/bulk`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); CreatedIssues response = check self.clientEp->post(resourcePath, request); return response; @@ -899,7 +883,7 @@ public isolated client class Client { remote isolated function bulkSetIssuesProperties(IssueEntityProperties payload) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/properties`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -907,7 +891,7 @@ public isolated client class Client { remote isolated function bulkSetIssueProperty(string propertyKey, BulkIssuePropertyUpdateRequest payload) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; @@ -915,7 +899,6 @@ public isolated client class Client { remote isolated function bulkDeleteIssueProperty(string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -931,7 +914,7 @@ public isolated client class Client { map queryParam = {notifyUsers: notifyUsers, overrideScreenSecurity: overrideScreenSecurity, overrideEditableFlag: overrideEditableFlag}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -941,14 +924,13 @@ public isolated client class Client { map queryParam = {deleteSubtasks: deleteSubtasks}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function assignIssue(string issueIdOrKey, User payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/assignee`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -978,7 +960,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Comment response = check self.clientEp->post(resourcePath, request); return response; @@ -995,7 +977,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Comment response = check self.clientEp->put(resourcePath, request); return response; @@ -1003,7 +985,6 @@ public isolated client class Client { remote isolated function deleteComment(string issueIdOrKey, string id) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/comment/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1017,7 +998,7 @@ public isolated client class Client { remote isolated function notify(string issueIdOrKey, Notification payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/notify`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -1035,7 +1016,7 @@ public isolated client class Client { remote isolated function setIssueProperty(string issueIdOrKey, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1043,7 +1024,6 @@ public isolated client class Client { remote isolated function deleteIssueProperty(string issueIdOrKey, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1057,7 +1037,7 @@ public isolated client class Client { remote isolated function createOrUpdateRemoteIssueLink(string issueIdOrKey, RemoteIssueLinkRequest payload) returns RemoteIssueLinkIdentifies|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/remotelink`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); RemoteIssueLinkIdentifies response = check self.clientEp->post(resourcePath, request); return response; @@ -1067,7 +1047,6 @@ public isolated client class Client { map queryParam = {globalId: globalId}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1079,7 +1058,7 @@ public isolated client class Client { remote isolated function updateRemoteIssueLink(string issueIdOrKey, string linkId, RemoteIssueLinkRequest payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/remotelink/${linkId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1087,7 +1066,6 @@ public isolated client class Client { remote isolated function deleteRemoteIssueLinkById(string issueIdOrKey, string linkId) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/remotelink/${linkId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1101,7 +1079,7 @@ public isolated client class Client { remote isolated function doTransition(string issueIdOrKey, IssueUpdateDetails payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/transitions`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -1114,14 +1092,12 @@ public isolated client class Client { remote isolated function addVote(string issueIdOrKey) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/votes`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> post(resourcePath, request); return response; } remote isolated function removeVote(string issueIdOrKey) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/votes`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1133,7 +1109,7 @@ public isolated client class Client { remote isolated function addWatcher(string issueIdOrKey, string payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/watchers`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -1143,7 +1119,6 @@ public isolated client class Client { map queryParam = {username: username, accountId: accountId}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1159,7 +1134,7 @@ public isolated client class Client { map queryParam = {notifyUsers: notifyUsers, adjustEstimate: adjustEstimate, newEstimate: newEstimate, reduceBy: reduceBy, expand: expand, overrideEditableFlag: overrideEditableFlag}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Worklog response = check self.clientEp->post(resourcePath, request); return response; @@ -1176,7 +1151,7 @@ public isolated client class Client { map queryParam = {notifyUsers: notifyUsers, adjustEstimate: adjustEstimate, newEstimate: newEstimate, expand: expand, overrideEditableFlag: overrideEditableFlag}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Worklog response = check self.clientEp->put(resourcePath, request); return response; @@ -1186,7 +1161,6 @@ public isolated client class Client { map queryParam = {notifyUsers: notifyUsers, adjustEstimate: adjustEstimate, newEstimate: newEstimate, increaseBy: increaseBy, overrideEditableFlag: overrideEditableFlag}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1203,7 +1177,7 @@ public isolated client class Client { remote isolated function setWorklogProperty(string issueIdOrKey, string worklogId, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/worklog/${worklogId}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1211,14 +1185,13 @@ public isolated client class Client { remote isolated function deleteWorklogProperty(string issueIdOrKey, string worklogId, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/issue/${issueIdOrKey}/worklog/${worklogId}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function linkIssues(LinkIssueRequestJsonBean payload) returns json|error { string resourcePath = string `/rest/api/2/issueLink`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -1231,7 +1204,6 @@ public isolated client class Client { remote isolated function deleteIssueLink(string linkId) returns http:Response | error { string resourcePath = string `/rest/api/2/issueLink/${linkId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1243,7 +1215,7 @@ public isolated client class Client { remote isolated function createIssueLinkType(IssueLinkType payload) returns IssueLinkType|error { string resourcePath = string `/rest/api/2/issueLinkType`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueLinkType response = check self.clientEp->post(resourcePath, request); return response; @@ -1256,7 +1228,7 @@ public isolated client class Client { remote isolated function updateIssueLinkType(string issueLinkTypeId, IssueLinkType payload) returns IssueLinkType|error { string resourcePath = string `/rest/api/2/issueLinkType/${issueLinkTypeId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueLinkType response = check self.clientEp->put(resourcePath, request); return response; @@ -1264,7 +1236,6 @@ public isolated client class Client { remote isolated function deleteIssueLinkType(string issueLinkTypeId) returns http:Response | error { string resourcePath = string `/rest/api/2/issueLinkType/${issueLinkTypeId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1293,7 +1264,7 @@ public isolated client class Client { remote isolated function createIssueType(IssueTypeCreateBean payload) returns IssueTypeDetails|error { string resourcePath = string `/rest/api/2/issuetype`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueTypeDetails response = check self.clientEp->post(resourcePath, request); return response; @@ -1306,7 +1277,7 @@ public isolated client class Client { remote isolated function updateIssueType(string id, IssueTypeUpdateBean payload) returns IssueTypeDetails|error { string resourcePath = string `/rest/api/2/issuetype/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueTypeDetails response = check self.clientEp->put(resourcePath, request); return response; @@ -1316,7 +1287,6 @@ public isolated client class Client { map queryParam = {alternativeIssueTypeId: alternativeIssueTypeId}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1346,7 +1316,7 @@ public isolated client class Client { remote isolated function setIssueTypeProperty(string issueTypeId, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/issuetype/${issueTypeId}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1354,7 +1324,6 @@ public isolated client class Client { remote isolated function deleteIssueTypeProperty(string issueTypeId, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/issuetype/${issueTypeId}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1368,7 +1337,7 @@ public isolated client class Client { remote isolated function createIssueTypeScheme(IssueTypeSchemeDetails payload) returns IssueTypeSchemeID|error { string resourcePath = string `/rest/api/2/issuetypescheme`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueTypeSchemeID response = check self.clientEp->post(resourcePath, request); return response; @@ -1390,7 +1359,7 @@ public isolated client class Client { remote isolated function assignIssueTypeSchemeToProject(IssueTypeSchemeProjectAssociation payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1398,7 +1367,7 @@ public isolated client class Client { remote isolated function updateIssueTypeScheme(int issueTypeSchemeId, IssueTypeSchemeUpdateDetails payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/${issueTypeSchemeId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1406,14 +1375,13 @@ public isolated client class Client { remote isolated function deleteIssueTypeScheme(int issueTypeSchemeId) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/${issueTypeSchemeId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } remote isolated function addIssueTypesToIssueTypeScheme(int issueTypeSchemeId, IssueTypeIds payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/${issueTypeSchemeId}/issuetype`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1421,7 +1389,7 @@ public isolated client class Client { remote isolated function reorderIssueTypesInIssueTypeScheme(int issueTypeSchemeId, OrderOfIssueTypes payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/${issueTypeSchemeId}/issuetype/move`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1429,7 +1397,6 @@ public isolated client class Client { remote isolated function removeIssueTypeFromIssueTypeScheme(int issueTypeSchemeId, int issueTypeId) returns json|error { string resourcePath = string `/rest/api/2/issuetypescheme/${issueTypeSchemeId}/issuetype/${issueTypeId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -1443,7 +1410,7 @@ public isolated client class Client { remote isolated function createIssueTypeScreenScheme(IssueTypeScreenSchemeDetails payload) returns IssueTypeScreenSchemeId|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueTypeScreenSchemeId response = check self.clientEp->post(resourcePath, request); return response; @@ -1465,7 +1432,7 @@ public isolated client class Client { remote isolated function assignIssueTypeScreenSchemeToProject(IssueTypeScreenSchemeProjectAssociation payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1473,7 +1440,7 @@ public isolated client class Client { remote isolated function updateIssueTypeScreenScheme(string issueTypeScreenSchemeId, IssueTypeScreenSchemeUpdateDetails payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/${issueTypeScreenSchemeId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1481,14 +1448,13 @@ public isolated client class Client { remote isolated function deleteIssueTypeScreenScheme(string issueTypeScreenSchemeId) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/${issueTypeScreenSchemeId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } remote isolated function appendMappingsForIssueTypeScreenScheme(string issueTypeScreenSchemeId, IssueTypeScreenSchemeMappingDetails payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/${issueTypeScreenSchemeId}/mapping`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1496,7 +1462,7 @@ public isolated client class Client { remote isolated function updateDefaultScreenScheme(string issueTypeScreenSchemeId, UpdateDefaultScreenScheme payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/${issueTypeScreenSchemeId}/mapping/default`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1504,7 +1470,7 @@ public isolated client class Client { remote isolated function removeMappingsFromIssueTypeScreenScheme(string issueTypeScreenSchemeId, IssueTypeIds payload) returns json|error { string resourcePath = string `/rest/api/2/issuetypescreenscheme/${issueTypeScreenSchemeId}/mapping/remove`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -1517,7 +1483,7 @@ public isolated client class Client { remote isolated function getAutoCompletePost(SearchAutoCompleteFilter payload) returns JQLReferenceData|error { string resourcePath = string `/rest/api/2/jql/autocompletedata`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); JQLReferenceData response = check self.clientEp->post(resourcePath, request); return response; @@ -1532,7 +1498,7 @@ public isolated client class Client { remote isolated function matchIssues(IssuesAndJQLQueries payload) returns IssueMatches|error { string resourcePath = string `/rest/api/2/jql/match`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); IssueMatches response = check self.clientEp->post(resourcePath, request); return response; @@ -1542,7 +1508,7 @@ public isolated client class Client { map queryParam = {validation: validation}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ParsedJqlQueries response = check self.clientEp->post(resourcePath, request); return response; @@ -1550,7 +1516,7 @@ public isolated client class Client { remote isolated function migrateQueries(JQLPersonalDataMigrationRequest payload) returns ConvertedJQLQueries|error { string resourcePath = string `/rest/api/2/jql/pdcleaner`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ConvertedJQLQueries response = check self.clientEp->post(resourcePath, request); return response; @@ -1581,7 +1547,7 @@ public isolated client class Client { map queryParam = {'key: 'key}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1591,7 +1557,6 @@ public isolated client class Client { map queryParam = {'key: 'key}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1603,7 +1568,7 @@ public isolated client class Client { remote isolated function setLocale(Locale payload) returns json|error { string resourcePath = string `/rest/api/2/mypreferences/locale`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1611,7 +1576,6 @@ public isolated client class Client { remote isolated function deleteLocale() returns json|error { string resourcePath = string `/rest/api/2/mypreferences/locale`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -1644,7 +1608,7 @@ public isolated client class Client { remote isolated function getBulkPermissions(BulkPermissionsRequestBean payload) returns BulkPermissionGrants|error { string resourcePath = string `/rest/api/2/permissions/check`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); BulkPermissionGrants response = check self.clientEp->post(resourcePath, request); return response; @@ -1652,7 +1616,7 @@ public isolated client class Client { remote isolated function getPermittedProjects(PermissionsKeysBean payload) returns PermittedProjects|error { string resourcePath = string `/rest/api/2/permissions/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PermittedProjects response = check self.clientEp->post(resourcePath, request); return response; @@ -1669,7 +1633,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PermissionScheme response = check self.clientEp->post(resourcePath, request); return response; @@ -1686,7 +1650,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PermissionScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -1694,7 +1658,6 @@ public isolated client class Client { remote isolated function deletePermissionScheme(int schemeId) returns http:Response | error { string resourcePath = string `/rest/api/2/permissionscheme/${schemeId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1710,7 +1673,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PermissionGrant response = check self.clientEp->post(resourcePath, request); return response; @@ -1725,7 +1688,6 @@ public isolated client class Client { remote isolated function deletePermissionSchemeEntity(int schemeId, int permissionId) returns http:Response | error { string resourcePath = string `/rest/api/2/permissionscheme/${schemeId}/permission/${permissionId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1749,7 +1711,7 @@ public isolated client class Client { remote isolated function createProject(ProjectInputBean payload) returns ProjectIdentifiers|error { string resourcePath = string `/rest/api/2/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectIdentifiers response = check self.clientEp->post(resourcePath, request); return response; @@ -1793,7 +1755,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Project response = check self.clientEp->put(resourcePath, request); return response; @@ -1803,21 +1765,19 @@ public isolated client class Client { map queryParam = {enableUndo: enableUndo}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function archiveProject(string projectIdOrKey) returns json|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/archive`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> post(resourcePath, request); return response; } remote isolated function updateProjectAvatar(string projectIdOrKey, Avatar payload) returns json|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/avatar`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1825,7 +1785,6 @@ public isolated client class Client { remote isolated function deleteProjectAvatar(string projectIdOrKey, int id) returns http:Response | error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/avatar/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1857,7 +1816,6 @@ public isolated client class Client { remote isolated function deleteProjectAsynchronously(string projectIdOrKey) returns TaskProgressBeanObject|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/delete`; http:Request request = new; - //TODO: Update the request as needed; TaskProgressBeanObject response = check self.clientEp-> post(resourcePath, request); return response; } @@ -1869,7 +1827,7 @@ public isolated client class Client { remote isolated function toggleFeatureForProject(string projectIdOrKey, string featureKey, ProjectFeatureToggleRequest payload) returns ProjectFeaturesResponse|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/features/${featureKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectFeaturesResponse response = check self.clientEp->put(resourcePath, request); return response; @@ -1887,7 +1845,7 @@ public isolated client class Client { remote isolated function setProjectProperty(string projectIdOrKey, string propertyKey, json payload) returns json|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -1895,14 +1853,12 @@ public isolated client class Client { remote isolated function deleteProjectProperty(string projectIdOrKey, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function restore(string projectIdOrKey) returns Project|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/restore`; http:Request request = new; - //TODO: Update the request as needed; Project response = check self.clientEp-> post(resourcePath, request); return response; } @@ -1919,7 +1875,7 @@ public isolated client class Client { remote isolated function setActors(string projectIdOrKey, int id, ProjectRoleActorsUpdateBean payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/role/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->put(resourcePath, request); return response; @@ -1927,7 +1883,7 @@ public isolated client class Client { remote isolated function addActorUsers(string projectIdOrKey, int id, ActorsMap payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/role/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->post(resourcePath, request); return response; @@ -1937,7 +1893,6 @@ public isolated client class Client { map queryParam = {user: user, 'group: 'group}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -1956,7 +1911,6 @@ public isolated client class Client { remote isolated function updateProjectType(string projectIdOrKey, string newProjectTypeKey) returns Project|error { string resourcePath = string `/rest/api/2/project/${projectIdOrKey}/type/${newProjectTypeKey}`; http:Request request = new; - //TODO: Update the request as needed; Project response = check self.clientEp-> put(resourcePath, request); return response; } @@ -1982,7 +1936,7 @@ public isolated client class Client { remote isolated function updateProjectEmail(int projectId, ProjectEmailAddress payload) returns json|error { string resourcePath = string `/rest/api/2/project/${projectId}/email`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -2016,7 +1970,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); PermissionScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2034,7 +1988,7 @@ public isolated client class Client { remote isolated function createProjectCategory(ProjectCategory payload) returns ProjectCategory|error { string resourcePath = string `/rest/api/2/projectCategory`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectCategory response = check self.clientEp->post(resourcePath, request); return response; @@ -2047,7 +2001,7 @@ public isolated client class Client { remote isolated function updateProjectCategory(int id, ProjectCategory payload) returns UpdatedProjectCategory|error { string resourcePath = string `/rest/api/2/projectCategory/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); UpdatedProjectCategory response = check self.clientEp->put(resourcePath, request); return response; @@ -2055,7 +2009,6 @@ public isolated client class Client { remote isolated function removeProjectCategory(int id) returns http:Response | error { string resourcePath = string `/rest/api/2/projectCategory/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2098,7 +2051,7 @@ public isolated client class Client { remote isolated function createProjectRole(CreateUpdateRoleRequestBean payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/role`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->post(resourcePath, request); return response; @@ -2111,7 +2064,7 @@ public isolated client class Client { remote isolated function fullyUpdateProjectRole(int id, CreateUpdateRoleRequestBean payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/role/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->put(resourcePath, request); return response; @@ -2119,7 +2072,7 @@ public isolated client class Client { remote isolated function partialUpdateProjectRole(int id, CreateUpdateRoleRequestBean payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/role/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->post(resourcePath, request); return response; @@ -2129,7 +2082,6 @@ public isolated client class Client { map queryParam = {swap: swap}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2141,7 +2093,7 @@ public isolated client class Client { remote isolated function addProjectRoleActorsToRole(int id, ActorInputBean payload) returns ProjectRole|error { string resourcePath = string `/rest/api/2/role/${id}/actors`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ProjectRole response = check self.clientEp->post(resourcePath, request); return response; @@ -2151,7 +2103,6 @@ public isolated client class Client { map queryParam = {user: user, 'group: 'group}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; ProjectRole response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -2165,7 +2116,7 @@ public isolated client class Client { remote isolated function createScreen(ScreenDetails payload) returns Screen|error { string resourcePath = string `/rest/api/2/screens`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Screen response = check self.clientEp->post(resourcePath, request); return response; @@ -2173,14 +2124,13 @@ public isolated client class Client { remote isolated function addFieldToDefaultScreen(string fieldId) returns json|error { string resourcePath = string `/rest/api/2/screens/addToDefault/${fieldId}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> post(resourcePath, request); return response; } remote isolated function updateScreen(int screenId, UpdateScreenDetails payload) returns Screen|error { string resourcePath = string `/rest/api/2/screens/${screenId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Screen response = check self.clientEp->put(resourcePath, request); return response; @@ -2188,7 +2138,6 @@ public isolated client class Client { remote isolated function deleteScreen(int screenId) returns http:Response | error { string resourcePath = string `/rest/api/2/screens/${screenId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2207,7 +2156,7 @@ public isolated client class Client { remote isolated function addScreenTab(int screenId, ScreenableTab payload) returns ScreenableTab|error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ScreenableTab response = check self.clientEp->post(resourcePath, request); return response; @@ -2215,7 +2164,7 @@ public isolated client class Client { remote isolated function renameScreenTab(int screenId, int tabId, ScreenableTab payload) returns ScreenableTab|error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ScreenableTab response = check self.clientEp->put(resourcePath, request); return response; @@ -2223,7 +2172,6 @@ public isolated client class Client { remote isolated function deleteScreenTab(int screenId, int tabId) returns http:Response | error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2237,7 +2185,7 @@ public isolated client class Client { remote isolated function addScreenTabField(int screenId, int tabId, AddFieldBean payload) returns ScreenableField|error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}/fields`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ScreenableField response = check self.clientEp->post(resourcePath, request); return response; @@ -2245,14 +2193,13 @@ public isolated client class Client { remote isolated function removeScreenTabField(int screenId, int tabId, string id) returns http:Response | error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}/fields/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function moveScreenTabField(int screenId, int tabId, string id, MoveFieldBean payload) returns json|error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}/fields/${id}/move`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -2260,7 +2207,6 @@ public isolated client class Client { remote isolated function moveScreenTab(int screenId, int tabId, int pos) returns json|error { string resourcePath = string `/rest/api/2/screens/${screenId}/tabs/${tabId}/move/${pos}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> post(resourcePath, request); return response; } @@ -2274,7 +2220,7 @@ public isolated client class Client { remote isolated function createScreenScheme(ScreenSchemeDetails payload) returns ScreenSchemeId|error { string resourcePath = string `/rest/api/2/screenscheme`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ScreenSchemeId response = check self.clientEp->post(resourcePath, request); return response; @@ -2282,7 +2228,7 @@ public isolated client class Client { remote isolated function updateScreenScheme(string screenSchemeId, UpdateScreenSchemeDetails payload) returns json|error { string resourcePath = string `/rest/api/2/screenscheme/${screenSchemeId}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -2290,7 +2236,6 @@ public isolated client class Client { remote isolated function deleteScreenScheme(string screenSchemeId) returns http:Response | error { string resourcePath = string `/rest/api/2/screenscheme/${screenSchemeId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2304,7 +2249,7 @@ public isolated client class Client { remote isolated function searchForIssuesUsingJqlPost(SearchRequestBean payload) returns SearchResults|error { string resourcePath = string `/rest/api/2/search`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); SearchResults response = check self.clientEp->post(resourcePath, request); return response; @@ -2358,7 +2303,6 @@ public isolated client class Client { remote isolated function cancelTask(string taskId) returns json|error { string resourcePath = string `/rest/api/2/task/${taskId}/cancel`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> post(resourcePath, request); return response; } @@ -2378,7 +2322,6 @@ public isolated client class Client { remote isolated function deleteAvatar(string 'type, string owningObjectId, int id) returns http:Response | error { string resourcePath = string `/rest/api/2/universal_avatar/'type/${'type}/owner/${owningObjectId}/avatar/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2392,7 +2335,7 @@ public isolated client class Client { remote isolated function createUser(UserWriteBean payload) returns User|error { string resourcePath = string `/rest/api/2/user`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); User response = check self.clientEp->post(resourcePath, request); return response; @@ -2402,7 +2345,6 @@ public isolated client class Client { map queryParam = {accountId: accountId, username: username, 'key: 'key}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2454,7 +2396,6 @@ public isolated client class Client { map queryParam = {accountId: accountId, username: username}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2512,7 +2453,7 @@ public isolated client class Client { map queryParam = {accountId: accountId, userKey: userKey, username: username}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -2522,7 +2463,6 @@ public isolated client class Client { map queryParam = {accountId: accountId, userKey: userKey, username: username}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2571,7 +2511,7 @@ public isolated client class Client { remote isolated function createVersion(Version payload) returns Version|error { string resourcePath = string `/rest/api/2/version`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Version response = check self.clientEp->post(resourcePath, request); return response; @@ -2586,7 +2526,7 @@ public isolated client class Client { remote isolated function updateVersion(string id, Version payload) returns Version|error { string resourcePath = string `/rest/api/2/version/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Version response = check self.clientEp->put(resourcePath, request); return response; @@ -2596,21 +2536,19 @@ public isolated client class Client { map queryParam = {moveFixIssuesTo: moveFixIssuesTo, moveAffectedIssuesTo: moveAffectedIssuesTo}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function mergeVersions(string id, string moveIssuesTo) returns json|error { string resourcePath = string `/rest/api/2/version/${id}/mergeto/${moveIssuesTo}`; http:Request request = new; - //TODO: Update the request as needed; json response = check self.clientEp-> put(resourcePath, request); return response; } remote isolated function moveVersion(string id, VersionMoveBean payload) returns Version|error { string resourcePath = string `/rest/api/2/version/${id}/move`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); Version response = check self.clientEp->post(resourcePath, request); return response; @@ -2623,7 +2561,7 @@ public isolated client class Client { remote isolated function deleteAndReplaceVersion(string id, DeleteAndReplaceVersionBean payload) returns json|error { string resourcePath = string `/rest/api/2/version/${id}/removeAndSwap`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->post(resourcePath, request); return response; @@ -2643,7 +2581,7 @@ public isolated client class Client { remote isolated function registerDynamicWebhooks(WebhookRegistrationDetails payload) returns ContainerForRegisteredWebhooks|error { string resourcePath = string `/rest/api/2/webhook`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); ContainerForRegisteredWebhooks response = check self.clientEp->post(resourcePath, request); return response; @@ -2651,7 +2589,6 @@ public isolated client class Client { remote isolated function deleteWebhookById() returns http:Response | error { string resourcePath = string `/rest/api/2/webhook`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2665,7 +2602,7 @@ public isolated client class Client { remote isolated function refreshWebhooks(ContainerForWebhookIDs payload) returns WebhooksExpirationDate|error { string resourcePath = string `/rest/api/2/webhook/refresh`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WebhooksExpirationDate response = check self.clientEp->put(resourcePath, request); return response; @@ -2680,7 +2617,7 @@ public isolated client class Client { remote isolated function createWorkflow(CreateWorkflowDetails payload) returns WorkflowIDs|error { string resourcePath = string `/rest/api/2/workflow`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowIDs response = check self.clientEp->post(resourcePath, request); return response; @@ -2695,7 +2632,7 @@ public isolated client class Client { remote isolated function updateWorkflowTransitionRuleConfigurations(WorkflowTransitionRulesUpdate payload) returns WorkflowTransitionRulesUpdateErrors|error { string resourcePath = string `/rest/api/2/workflow/rule/config`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowTransitionRulesUpdateErrors response = check self.clientEp->put(resourcePath, request); return response; @@ -2719,7 +2656,7 @@ public isolated client class Client { map queryParam = {'key: 'key, workflowName: workflowName, workflowMode: workflowMode}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowTransitionProperty response = check self.clientEp->put(resourcePath, request); return response; @@ -2729,7 +2666,7 @@ public isolated client class Client { map queryParam = {'key: 'key, workflowName: workflowName, workflowMode: workflowMode}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowTransitionProperty response = check self.clientEp->post(resourcePath, request); return response; @@ -2739,14 +2676,12 @@ public isolated client class Client { map queryParam = {'key: 'key, workflowName: workflowName, workflowMode: workflowMode}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function deleteInactiveWorkflow(string entityId) returns http:Response | error { string resourcePath = string `/rest/api/2/workflow/${entityId}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2760,7 +2695,7 @@ public isolated client class Client { remote isolated function createWorkflowScheme(WorkflowScheme payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->post(resourcePath, request); return response; @@ -2775,7 +2710,7 @@ public isolated client class Client { remote isolated function assignSchemeToProject(WorkflowSchemeProjectAssociation payload) returns json|error { string resourcePath = string `/rest/api/2/workflowscheme/project`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); json response = check self.clientEp->put(resourcePath, request); return response; @@ -2790,7 +2725,7 @@ public isolated client class Client { remote isolated function updateWorkflowScheme(int id, WorkflowScheme payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2798,14 +2733,12 @@ public isolated client class Client { remote isolated function deleteWorkflowScheme(int id) returns http:Response | error { string resourcePath = string `/rest/api/2/workflowscheme/${id}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } remote isolated function createWorkflowSchemeDraftFromParent(int id) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/createdraft`; http:Request request = new; - //TODO: Update the request as needed; WorkflowScheme response = check self.clientEp-> post(resourcePath, request); return response; } @@ -2819,7 +2752,7 @@ public isolated client class Client { remote isolated function updateDefaultWorkflow(int id, DefaultWorkflow payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/default`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2829,7 +2762,6 @@ public isolated client class Client { map queryParam = {updateDraftIfNeeded: updateDraftIfNeeded}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; WorkflowScheme response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -2841,7 +2773,7 @@ public isolated client class Client { remote isolated function updateWorkflowSchemeDraft(int id, WorkflowScheme payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2849,7 +2781,6 @@ public isolated client class Client { remote isolated function deleteWorkflowSchemeDraft(int id) returns http:Response | error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2861,7 +2792,7 @@ public isolated client class Client { remote isolated function updateDraftDefaultWorkflow(int id, DefaultWorkflow payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft/default`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2869,7 +2800,6 @@ public isolated client class Client { remote isolated function deleteDraftDefaultWorkflow(int id) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft/default`; http:Request request = new; - //TODO: Update the request as needed; WorkflowScheme response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -2881,7 +2811,7 @@ public isolated client class Client { remote isolated function setWorkflowSchemeDraftIssueType(int id, string issueType, IssueTypeWorkflowMapping payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft/issuetype/${issueType}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2889,7 +2819,6 @@ public isolated client class Client { remote isolated function deleteWorkflowSchemeDraftIssueType(int id, string issueType) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/draft/issuetype/${issueType}`; http:Request request = new; - //TODO: Update the request as needed; WorkflowScheme response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -2905,7 +2834,7 @@ public isolated client class Client { map queryParam = {workflowName: workflowName}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2915,7 +2844,6 @@ public isolated client class Client { map queryParam = {workflowName: workflowName}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2929,7 +2857,7 @@ public isolated client class Client { remote isolated function setWorkflowSchemeIssueType(int id, string issueType, IssueTypeWorkflowMapping payload) returns WorkflowScheme|error { string resourcePath = string `/rest/api/2/workflowscheme/${id}/issuetype/${issueType}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2939,7 +2867,6 @@ public isolated client class Client { map queryParam = {updateDraftIfNeeded: updateDraftIfNeeded}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; WorkflowScheme response = check self.clientEp-> delete(resourcePath, request); return response; } @@ -2955,7 +2882,7 @@ public isolated client class Client { map queryParam = {workflowName: workflowName}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorkflowScheme response = check self.clientEp->put(resourcePath, request); return response; @@ -2965,7 +2892,6 @@ public isolated client class Client { map queryParam = {workflowName: workflowName, updateDraftIfNeeded: updateDraftIfNeeded}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -2981,7 +2907,7 @@ public isolated client class Client { map queryParam = {expand: expand}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); WorklogArr response = check self.clientEp->post(resourcePath, request); return response; @@ -3006,7 +2932,7 @@ public isolated client class Client { remote isolated function 'AddonPropertiesResource\.putAddonProperty\_put(string addonKey, string propertyKey, json payload) returns OperationMessage|error { string resourcePath = string `/rest/atlassian-connect/1/addons/${addonKey}/properties/${propertyKey}`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); OperationMessage response = check self.clientEp->put(resourcePath, request); return response; @@ -3014,7 +2940,6 @@ public isolated client class Client { remote isolated function 'AddonPropertiesResource\.deleteAddonProperty\_delete(string addonKey, string propertyKey) returns http:Response | error { string resourcePath = string `/rest/atlassian-connect/1/addons/${addonKey}/properties/${propertyKey}`; http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } @@ -3026,7 +2951,7 @@ public isolated client class Client { remote isolated function 'DynamicModulesResource\.registerModules\_post(ConnectModules payload) returns http:Response | error { string resourcePath = string `/rest/atlassian-connect/1/app/module/dynamic`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -3036,7 +2961,6 @@ public isolated client class Client { map queryParam = {moduleKey: moduleKey}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> delete(resourcePath, request ); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiline_param_comment.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiline_param_comment.bal new file mode 100644 index 000000000..eccb5e0be --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiline_param_comment.bal @@ -0,0 +1,60 @@ +import ballerina/http; + +# APIs for fine-tuning and managing deployments of OpenAI models. +public isolated client class Client { + final http:Client clientEp; + final readonly & ApiKeysConfig apiKeyConfig; + # Gets invoked to initialize the `connector`. + # + # + apiKeyConfig - API keys for authorization + # + 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(ApiKeysConfig apiKeyConfig, string serviceUrl, ConnectionConfig config = {}) returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); + return; + } + # Gets the events for the fine-tune job specified by the given fine-tune-id. + # Events are created when the job status changes, e.g. running or complete, and when results are uploaded. + # + # + fineTuneId - The identifier of the fine-tune job. + # + 'stream - A flag indicating whether to stream events for the fine-tune job. If set to true, + # events will be sent as data-only server-sent events as they become available. The stream will terminate with + # a data: [DONE] message when the job is finished (succeeded, cancelled, or failed). + # If set to false, only events generated so far will be returned.. + # + apiVersion - The requested API version. + # + return - Success + remote isolated function fineTunes_GetEvents(string fineTuneId, string apiVersion, boolean? 'stream = ()) returns EventList|error { + string resourcePath = string `/fine-tunes/${getEncodedUri(fineTuneId)}/events`; + map queryParam = {"stream": 'stream, "api-version": apiVersion}; + resourcePath = resourcePath + check getPathForQueryParam(queryParam); + map headerValues = {"api-key": self.apiKeyConfig.apiKey}; + map httpHeaders = getMapForHeaders(headerValues); + EventList response = check self.clientEp->get(resourcePath, httpHeaders); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiple_pathparam.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiple_pathparam.bal index 09b17d0ae..1edce9cda 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiple_pathparam.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/multiple_pathparam.bal @@ -1,25 +1,47 @@ -import ballerina/http; +import ballerina/http; # Title public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # - # + 'version - test + # + version - test # + name - test # + return - Ok - remote isolated function pathParameter(int 'version, string name) returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri(name)}`; - string response = check self.clientEp-> get(resourcePath); + remote isolated function pathParameter(int version, string name) returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri(name)}`; + string response = check self.clientEp->get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_response.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_response.bal index 2e3718864..9a46f5281 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_response.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_response.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_union_response.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_union_response.bal index f29543bc7..b7c79ddc3 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_union_response.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/nillable_union_response.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore/v1") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/openapi_weather_api.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/openapi_weather_api.bal index 5205e07be..33550068e 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/openapi_weather_api.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/openapi_weather_api.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. - string appid; -|}; - # 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**: 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. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,33 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; @@ -35,11 +51,11 @@ public isolated client class Client { # + mode - **Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default. # + return - Successful response @display {label: "Current Weather"} - remote isolated function getCurretWeatherData(@display {label: "CityName or StateCode or CountryCode"} string? q = (), @display {label: "City Id"} string? id = (), @display {label: "Latitude"} string? lat = (), @display {label: "Longitude"} string? lon = (), @display {label: "Zip Code"} string? zip = (), @display {label: "Units"} string units = "imperial", @display {label: "Language"} string lang = "en", @display {label: "Mode"} string mode = "json") returns CurrentWeatherData|error { + remote isolated function getCurretWeatherData(@display {label: "CityName or StateCode or CountryCode"} string? q = (), @display {label: "City Id"} string? id = (), @display {label: "Latitude"} string? lat = (), @display {label: "Longitude"} string? lon = (), @display {label: "Zip Code"} string? zip = (), @display {label: "Units"} "standard"|"metric"|"imperial" units = "imperial", @display {label: "Language"} "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" lang = "en", @display {label: "Mode"} "json"|"xml"|"html" mode = "json") returns CurrentWeatherData|error { string resourcePath = string `/weather`; map queryParam = {"q": q, "id": id, "lat": lat, "lon": lon, "zip": zip, "units": units, "lang": lang, "mode": mode, "appid": self.apiKeyConfig.appid}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - CurrentWeatherData response = check self.clientEp-> get(resourcePath); + CurrentWeatherData response = check self.clientEp->get(resourcePath); return response; } # Provide weather forecast for any geographical coordinates @@ -51,11 +67,11 @@ public isolated client class Client { # + lang - **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`. # + return - Successful response @display {label: "Weather Forecast"} - remote isolated function getWeatherForecast(@display {label: "Latitude"} string lat, @display {label: "Longtitude"} string lon, @display {label: "Exclude"} string? exclude = (), @display {label: "Units"} string? units = (), @display {label: "Language"} string? lang = ()) returns WeatherForecast|error { + remote isolated function getWeatherForecast(@display {label: "Latitude"} string lat, @display {label: "Longtitude"} string lon, @display {label: "Exclude"} "current"|"minutely"|"hourly"|"daily"|"alerts"? exclude = (), @display {label: "Units"} string? units = (), @display {label: "Language"} string? lang = ()) returns WeatherForecast|error { string resourcePath = string `/onecall`; map queryParam = {"lat": lat, "lon": lon, "exclude": exclude, "units": units, "lang": lang, "appid": self.apiKeyConfig.appid}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); - WeatherForecast response = check self.clientEp-> get(resourcePath); + WeatherForecast response = check self.clientEp->get(resourcePath); return response; } } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/operation.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/operation.bal index 7f3949063..0c447f8ff 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/operation.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/operation.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/tag.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/tag.bal index a1c20df58..2c4a0a4d4 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/tag.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/tag.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api-cov19.now.sh/") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/uber_openapi.bal b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/uber_openapi.bal index 5b270c125..31d999cb9 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/uber_openapi.bal +++ b/openapi-cli/src/test/resources/generators/client/file_provider/ballerina/uber_openapi.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # Uber API Key - string serverToken; -|}; - # Move your app forward with the Uber API public isolated client class Client { final http:Client clientEp; @@ -13,11 +7,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api.uber.com/v1") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "https://api.uber.com/v1") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; @@ -29,35 +54,35 @@ public isolated client class Client { # + return - An array of products remote isolated function getProducts(decimal latitude, decimal longitude) returns Product[]|error { string resourcePath = string `/products`; - map queryParam = {"latitude": latitude, "longitude": longitude, "server_token": self.apiKeyConfig.serverToken}; + map queryParam = {"latitude": latitude, "longitude": longitude, "server_token": self.apiKeyConfig.server_token}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); Product[] response = check self.clientEp->get(resourcePath); return response; } # Price Estimates # - # + startLatitude - Latitude component of start location. - # + startLongitude - Longitude component of start location. - # + endLatitude - Latitude component of end location. - # + endLongitude - Longitude component of end location. + # + start_latitude - Latitude component of start location. + # + start_longitude - Longitude component of start location. + # + end_latitude - Latitude component of end location. + # + end_longitude - Longitude component of end location. # + return - An array of price estimates by product - remote isolated function getPrice(decimal startLatitude, decimal startLongitude, decimal endLatitude, decimal endLongitude) returns PriceEstimate[]|error { + remote isolated function getPrice(decimal start_latitude, decimal start_longitude, decimal end_latitude, decimal end_longitude) returns PriceEstimate[]|error { string resourcePath = string `/estimates/price`; - map queryParam = {"start_latitude": startLatitude, "start_longitude": startLongitude, "end_latitude": endLatitude, "end_longitude": endLongitude}; + map queryParam = {"start_latitude": start_latitude, "start_longitude": start_longitude, "end_latitude": end_latitude, "end_longitude": end_longitude}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); PriceEstimate[] response = check self.clientEp->get(resourcePath); return response; } # Time Estimates # - # + startLatitude - Latitude component of start location. - # + startLongitude - Longitude component of start location. - # + customerUuid - Unique customer identifier to be used for experience customization. - # + productId - Unique identifier representing a specific product for a given latitude & longitude. + # + start_latitude - Latitude component of start location. + # + start_longitude - Longitude component of start location. + # + customer_uuid - Unique customer identifier to be used for experience customization. + # + product_id - Unique identifier representing a specific product for a given latitude & longitude. # + return - An array of products - remote isolated function getTimeEstimates(decimal startLatitude, decimal startLongitude, string? customerUuid = (), string? productId = ()) returns Product[]|error { + remote isolated function getTimeEstimates(decimal start_latitude, decimal start_longitude, string? customer_uuid = (), string? product_id = ()) returns Product[]|error { string resourcePath = string `/estimates/time`; - map queryParam = {"start_latitude": startLatitude, "start_longitude": startLongitude, "customer_uuid": customerUuid, "product_id": productId}; + map queryParam = {"start_latitude": start_latitude, "start_longitude": start_longitude, "customer_uuid": customer_uuid, "product_id": product_id}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); Product[] response = check self.clientEp->get(resourcePath); return response; diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/description_with_special_characters.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/description_with_special_characters.yaml new file mode 100644 index 000000000..330c08294 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/description_with_special_characters.yaml @@ -0,0 +1,69 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + parameters: + - name: auto-unicode + in: query + description: "Specifies how to deal with message text that contains characters\ + \ not present in the GSM 03.38 character set.\n\nMessages that contain only\ + \ GSM 03.38 characters are not affected by this setting. \nIf the value\ + \ is `true` then a message containing non-GSM 03.38 characters will be transmitted\ + \ as a Unicode SMS (which is most likely more costly). \n\nPlease note:\ + \ when `auto-unicode` is `true` and the value of the `encoding` property\ + \ is specified as `UNICODE`, the message will always be sent as `UNICODE`.\n\ + \nIf the value is `false` and the `encoding` property is `TEXT` then non-GSM\ + \ 03.38 characters will be replaced by the `?` character.\n\nWhen using\ + \ this setting on the API, you should take case to ensure that your message\ + \ is _clean_. \n\nInvisible unicode and unexpected characters could unintentionally\ + \ convert an message to `UNICODE`. A common mistake is to use the backtick\ + \ character (\\`) which is unicode and will turn your `TEXT` message into\ + \ a `UNICODE` message.\n" + schema: + type: boolean + default: false + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: {} + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: {} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_0.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_0.yaml new file mode 100644 index 000000000..a72e8f1cf --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_0.yaml @@ -0,0 +1,112 @@ +openapi: 3.0.1 +info: + title: Format REST API + version: 4.0.0 +paths: + /projects: + get: + operationId: op1 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/StringObject' + post: + operationId: op2 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/IntegerObject' + delete: + operationId: op3 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/NumberObject' +servers: + - url: https://app.launchdarkly.com/api/v2 +components: + schemas: + StringObject: + type: object + properties: + name: + type: string + byteContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: byte + binaryContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: binary + uuidContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: uuid + uriContent: + type: string + format: uri + pattern: ^[a-zA-Z][a-zA-Z0-9+.-]*:[a-zA-Z0-9+.-]+$ + dateContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date + passwordContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: password + datetimeContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date-time + emailContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: email + hostnameContent: + type: string + format: hostname + pattern: ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])*$ + ipv4Content: + type: string + format: ipv4 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + ipv6Content: + type: string + format: ipv6 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + IntegerObject: + type: object + properties: + name: + type: string + int32Content: + type: integer + format: int32 + maximum: 2147483647 + int64Content: + type: integer + format: int64 + minimum: 0 + NumberObject: + type: object + properties: + name: + type: string + floatContent: + type: number + format: float + minimum: 0.1 + doubleContent: + type: number + format: double + maximum: 200 diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_1.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_1.yaml new file mode 100644 index 000000000..00808fa5b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/format_types_v3_1.yaml @@ -0,0 +1,112 @@ +openapi: 3.1.0 +info: + title: Format REST API + version: 4.0.0 +paths: + /projects: + get: + operationId: op1 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/StringObject' + post: + operationId: op2 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/IntegerObject' + delete: + operationId: op3 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/NumberObject' +servers: + - url: https://app.launchdarkly.com/api/v2 +components: + schemas: + StringObject: + type: object + properties: + name: + type: string + byteContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: byte + binaryContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: binary + uuidContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: uuid + uriContent: + type: string + format: uri + pattern: ^[a-zA-Z][a-zA-Z0-9+.-]*:[a-zA-Z0-9+.-]+$ + dateContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date + passwordContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: password + datetimeContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date-time + emailContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: email + hostnameContent: + type: string + format: hostname + pattern: ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])*$ + ipv4Content: + type: string + format: ipv4 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + ipv6Content: + type: string + format: ipv6 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + IntegerObject: + type: object + properties: + name: + type: string + int32Content: + type: integer + format: int32 + maximum: 2147483647 + int64Content: + type: integer + format: int64 + minimum: 0 + NumberObject: + type: object + properties: + name: + type: string + floatContent: + type: number + format: float + minimum: 0.1 + doubleContent: + type: number + format: double + maximum: 200 diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/header_with_enum.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/header_with_enum.yaml new file mode 100644 index 000000000..c597de28a --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/header_with_enum.yaml @@ -0,0 +1,46 @@ +openapi: 3.0.1 +info: + title: Swagger Petstore - OpenAPI 3.1 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + parameters: + - name: X-CLIENT + in: header + schema: + type: array + items: + type: string + enum: + - X + - Y + - Z + responses: + "200": + description: "successful operation" + content: + application/json: + schema: + additionalProperties: + type: "integer" + format: "int32" +components: {} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/incorrect_format.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/incorrect_format.yaml new file mode 100644 index 000000000..2cc1c7bea --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/incorrect_format.yaml @@ -0,0 +1,129 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: false + explode: true + schema: + type: string + default: available + enum: + - available + - pending + - sold + - name: limit + in: query + description: The number of client accounts to return on each page of results. + The default value is `50`. Entering a `limit` value less than the minimum + (`10`) or greater than the maximum (`50`) is ignored and the system uses + the default values. Depending on the `limit` you specify, the system determines + the `offset` parameter to use (number of records to skip) and includes it + in the link used to get the next page of results. + schema: + maximum: 50 + minimum: 10 + type: string + format: int32 + default: "50" + example: "50" + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' +components: + schemas: + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: tag + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + example: 10 + name: + type: string + example: doggie + photoUrls: + type: array + xml: + wrapped: true + items: + type: string + xml: + name: photoUrl + tags: + type: array + xml: + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiline_param_comment.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiline_param_comment.yaml new file mode 100644 index 000000000..4e823f14f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiline_param_comment.yaml @@ -0,0 +1,165 @@ +openapi: 3.0.1 +info: + title: Azure OpenAI API version 2022-12-01 + description: APIs for fine-tuning and managing deployments of OpenAI models. + version: 2022-12-01 +servers: + - url: / +security: + - api-key: [] +paths: + /fine-tunes/{fine-tune-id}/events: + get: + tags: + - 'Fine-tunes:' + summary: "Gets the events for the fine-tune job specified by the given fine-tune-id.\r\ + \nEvents are created when the job status changes, e.g. running or complete,\ + \ and when results are uploaded." + operationId: FineTunes_GetEvents + parameters: + - name: fine-tune-id + in: path + description: The identifier of the fine-tune job. + required: true + schema: + type: string + - name: stream + in: query + description: "A flag indicating whether to stream events for the fine-tune\ + \ job. If set to true,\r\n events will be sent as data-only server-sent\ + \ events as they become available. The stream will terminate with\r\n \ + \ a data: [DONE] message when the job is finished (succeeded, cancelled,\ + \ or failed).\r\n If set to false, only events generated so far\ + \ will be returned.." + schema: + type: boolean + - name: api-version + in: query + description: The requested API version. + required: true + schema: + type: string + x-ms-client-default: 2022-12-01 + x-ms-parameter-location: client + x-ms-client-default: 2022-12-01 + x-ms-parameter-location: client + responses: + 200: + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/EventList' + text/event-stream: + schema: + $ref: '#/components/schemas/EventList' +components: + schemas: + Event: + title: Event + required: + - created_at + - level + - message + type: object + properties: + object: + $ref: '#/components/schemas/TypeDiscriminator' + created_at: + type: integer + description: A timestamp when this event was created (in unix epochs). + format: unixtime + level: + $ref: '#/components/schemas/LogLevel' + message: + minLength: 1 + type: string + description: The message describing the event. This can be a change of state, + e.g., enqueued, started, failed or completed, or other events like uploaded + results. + EventList: + title: EventList + type: object + properties: + object: + $ref: '#/components/schemas/TypeDiscriminator' + data: + type: array + description: The list of items. + items: + $ref: '#/components/schemas/Event' + description: Represents a list of events. + InnerError: + title: InnerError + type: object + properties: + code: + $ref: '#/components/schemas/InnerErrorCode' + innererror: + $ref: '#/components/schemas/InnerError' + description: "Inner error as defined in the Microsoft REST guidelines\r\n(https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses)." + InnerErrorCode: + title: InnerErrorCode + type: string + description: "Inner error codes as defined in the Microsoft REST guidelines\r\ + \n(https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses)." + enum: + - invalidPayload + x-ms-enum: + name: InnerErrorCode + modelAsString: true + values: + - value: invalidPayload + description: The request data is invalid for this operation. + LogLevel: + title: LogLevel + type: string + description: The verbosity level of an event. + enum: + - info + - warning + - error + x-ms-enum: + name: LogLevel + modelAsString: true + values: + - value: info + description: This event is for information only. + - value: warning + description: This event represents a mitigated issue. + - value: error + description: This message represents a non recoverable issue. + TypeDiscriminator: + title: TypeDiscriminator + type: string + description: Defines the type of an object. + enum: + - list + - fine-tune + - file + - fine-tune-event + - model + - deployment + x-ms-enum: + name: TypeDiscriminator + modelAsString: true + values: + - value: list + description: This object represents a list of other objects. + - value: fine-tune + description: This object represents a fine tune job. + - value: file + description: This object represents a file. + - value: fine-tune-event + description: This object represents an event of a fine tune job. + - value: model + description: This object represents a model (can be a base models or fine + tune job result). + - value: deployment + description: This object represents a deployment. + securitySchemes: + api-key: + type: apiKey + description: Provide your Cognitive Services Azure OpenAI account key here. + name: api-key + in: header diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiple_pathparam.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiple_pathparam.yaml index c522ab037..64e41d5ad 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiple_pathparam.yaml +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/multiple_pathparam.yaml @@ -16,7 +16,6 @@ paths: description: test schema: type: integer - format: int32 - name: name in: path required: true diff --git a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/uber_openapi.yaml b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/uber_openapi.yaml index 2c69b389e..0d477be4e 100644 --- a/openapi-cli/src/test/resources/generators/client/file_provider/swagger/uber_openapi.yaml +++ b/openapi-cli/src/test/resources/generators/client/file_provider/swagger/uber_openapi.yaml @@ -196,13 +196,11 @@ paths: description: Offset the list of returned results by this amount. Default is zero. schema: type: integer - format: int32 - name: limit in: query description: Number of items to retrieve. Default is 5, maximum is 100. schema: type: integer - format: int32 tags: - User responses: diff --git a/openapi-cli/src/test/resources/generators/client/resource/ballerina/all_methods.bal b/openapi-cli/src/test/resources/generators/client/resource/ballerina/all_methods.bal index 5aab5cb93..1eeaeee60 100644 --- a/openapi-cli/src/test/resources/generators/client/resource/ballerina/all_methods.bal +++ b/openapi-cli/src/test/resources/generators/client/resource/ballerina/all_methods.bal @@ -1,24 +1,47 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key to authorize requests. - string appid1; - # API key to authorize requests. - string appid2; -|}; - public isolated client class Client { final http:Client clientEp; final readonly & ApiKeysConfig apiKeyConfig; # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; @@ -42,7 +65,6 @@ public isolated client class Client { map queryParam = {"appid1": self.apiKeyConfig.appid1, "appid2": self.apiKeyConfig.appid2}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> put(resourcePath, request); return response; } @@ -54,7 +76,6 @@ public isolated client class Client { map queryParam = {"appid1": self.apiKeyConfig.appid1, "appid2": self.apiKeyConfig.appid2}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Request request = new; - //TODO: Update the request as needed; http:Response response = check self.clientEp-> post(resourcePath, request); return response; } diff --git a/openapi-cli/src/test/resources/generators/client/resource/ballerina/header.bal b/openapi-cli/src/test/resources/generators/client/resource/ballerina/header.bal index db438de66..418590b46 100644 --- a/openapi-cli/src/test/resources/generators/client/resource/ballerina/header.bal +++ b/openapi-cli/src/test/resources/generators/client/resource/ballerina/header.bal @@ -1,11 +1,5 @@ import ballerina/http; -# Provides API key configurations needed when communicating with a remote HTTP endpoint. -public type ApiKeysConfig record {| - # API key. - string appid; -|}; - # Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. @display {label: "Open Weather Client"} public isolated client class Client { @@ -14,11 +8,42 @@ public isolated client class Client { # Gets invoked to initialize the `connector`. # # + apiKeyConfig - API keys for authorization - # + clientConfig - The configurations to be used when initializing 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(ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ApiKeysConfig apiKeyConfig, ConnectionConfig config = {}, string serviceUrl = "http://api.openweathermap.org/data/2.5/") returns error? { + http:ClientConfiguration httpClientConfig = { + httpVersion: config.httpVersion, + timeout: config.timeout, + forwarded: config.forwarded, + poolConfig: config.poolConfig, + compression: config.compression, + circuitBreaker: config.circuitBreaker, + retryConfig: config.retryConfig, + validation: config.validation + }; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; self.apiKeyConfig = apiKeyConfig.cloneReadOnly(); return; diff --git a/openapi-cli/src/test/resources/generators/client/resource/ballerina/pathParameters.bal b/openapi-cli/src/test/resources/generators/client/resource/ballerina/pathParameters.bal index 13bc26d94..9cfe43ca0 100644 --- a/openapi-cli/src/test/resources/generators/client/resource/ballerina/pathParameters.bal +++ b/openapi-cli/src/test/resources/generators/client/resource/ballerina/pathParameters.bal @@ -4,11 +4,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "localhost:9090/payloadV") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } @@ -25,7 +47,6 @@ public isolated client class Client { resource isolated function post .() returns string|error { string resourcePath = string `/`; http:Request request = new; - //TODO: Update the request as needed; string response = check self.clientEp-> post(resourcePath, request); return response; } @@ -40,15 +61,15 @@ public isolated client class Client { } # # + return - Ok - resource isolated function get v1/[int 'version]/v2/[string name]() returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri(name)}`; + resource isolated function get v1/[int version]/v2/[string name]() returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri(name)}`; string response = check self.clientEp->get(resourcePath); return response; } # # + return - Ok - resource isolated function get v1/[int 'version]/v2/[int 'limit]() returns string|error { - string resourcePath = string `/v1/${getEncodedUri('version)}/v2/${getEncodedUri('limit)}`; + resource isolated function get v1/[int version]/v2/[int 'limit]() returns string|error { + string resourcePath = string `/v1/${getEncodedUri(version)}/v2/${getEncodedUri('limit)}`; string response = check self.clientEp->get(resourcePath); return response; } @@ -61,15 +82,15 @@ public isolated client class Client { } # Retrieves a single customer. # - # + customerId - Customer ID + # + customer_id - Customer ID # + fields - Show only certain fields, specified by a comma-separated list of field names. # + return - Requested customer - resource isolated function get admin/api/'2021\-10/customers/[string customerIdJson](string? fields = ()) returns http:Response|error { - if !customerIdJson.endsWith(".json") { + resource isolated function get admin/api/'2021\-10/customers/[string customer_idJson](string? fields = ()) returns http:Response|error { + if !customer_idJson.endsWith(".json") { return error("bad URL"); } - string customerId = customerIdJson.substring(0, customerIdJson.length() - 4); - string resourcePath = string `/admin/api/2021-10/customers/${getEncodedUri(customerId)}.json`; + string customer_id = customer_idJson.substring(0, customer_idJson.length() - 4); + string resourcePath = string `/admin/api/2021-10/customers/${getEncodedUri(customer_id)}.json`; map queryParam = {"fields": fields}; resourcePath = resourcePath + check getPathForQueryParam(queryParam); http:Response response = check self.clientEp->get(resourcePath); diff --git a/openapi-cli/src/test/resources/generators/client/resource/ballerina/reference_path.bal b/openapi-cli/src/test/resources/generators/client/resource/ballerina/reference_path.bal new file mode 100644 index 000000000..e72041ace --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/resource/ballerina/reference_path.bal @@ -0,0 +1,46 @@ +import ballerina/http; + +public isolated client class Client { + final http:Client clientEp; + # 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(ConnectionConfig config = {}, string serviceUrl = "http://localhost") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); + self.clientEp = httpEp; + return; + } + # + # + id - Id of the point + # + return - Accepted + resource isolated function post pet/[Param id]() returns http:Response|error { + string resourcePath = string `/pet/${getEncodedUri(id)}`; + http:Request request = new; + http:Response response = check self.clientEp-> post(resourcePath, request); + return response; + } +} diff --git a/openapi-cli/src/test/resources/generators/client/resource/ballerina/request_body.bal b/openapi-cli/src/test/resources/generators/client/resource/ballerina/request_body.bal index f85ca8dbc..d9d890f5f 100644 --- a/openapi-cli/src/test/resources/generators/client/resource/ballerina/request_body.bal +++ b/openapi-cli/src/test/resources/generators/client/resource/ballerina/request_body.bal @@ -6,21 +6,43 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://petstore.swagger.io:443/v2") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } # 02 Example for rb has inline requestbody. # # + return - OK - resource isolated function put path01(Path01Body payload) returns http:Response|error { + resource isolated function put path01(Path01_body payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; @@ -31,7 +53,7 @@ public isolated client class Client { resource isolated function post path01(User payload) returns http:Response|error { string resourcePath = string `/path01`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -43,7 +65,7 @@ public isolated client class Client { resource isolated function put path02(User payload) returns http:Response|error { string resourcePath = string `/path02`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->put(resourcePath, request); return response; @@ -54,7 +76,7 @@ public isolated client class Client { resource isolated function post path02(User[] payload) returns http:Response|error { string resourcePath = string `/path02`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); request.setPayload(jsonBody, "application/json"); http:Response response = check self.clientEp->post(resourcePath, request); return response; @@ -62,10 +84,10 @@ public isolated client class Client { # 06 Example for rb has array inline requestbody. # # + return - OK - resource isolated function put path03(Path03Body payload) returns http:Response|error { + resource isolated function put path03(Path03_body payload) returns http:Response|error { string resourcePath = string `/path03`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->put(resourcePath, request); @@ -74,10 +96,10 @@ public isolated client class Client { # 05 Example for rb has array inline requestbody. # # + return - OK - resource isolated function post path03(Path03Body1 payload) returns http:Response|error { + resource isolated function post path03(Path03_body_1 payload) returns http:Response|error { string resourcePath = string `/path03`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); @@ -86,10 +108,10 @@ public isolated client class Client { # 07 Example for rb has array inline requestbody. # # + return - OK - resource isolated function post path04(Path04Body[] payload) returns http:Response|error { + resource isolated function post path04(Path04_body[] payload) returns http:Response|error { string resourcePath = string `/path04`; http:Request request = new; - json jsonBody = check payload.cloneWithType(json); + json jsonBody = payload.toJson(); xml? xmlBody = check xmldata:fromJson(jsonBody); request.setPayload(xmlBody, "application/xml"); http:Response response = check self.clientEp->post(resourcePath, request); diff --git a/openapi-cli/src/test/resources/generators/client/resource/swagger/all_methods.yaml b/openapi-cli/src/test/resources/generators/client/resource/swagger/all_methods.yaml index 08bac5432..be234e0d7 100644 --- a/openapi-cli/src/test/resources/generators/client/resource/swagger/all_methods.yaml +++ b/openapi-cli/src/test/resources/generators/client/resource/swagger/all_methods.yaml @@ -48,7 +48,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/client/resource/swagger/reference_path.yaml b/openapi-cli/src/test/resources/generators/client/resource/swagger/reference_path.yaml new file mode 100644 index 000000000..a70c61d31 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/resource/swagger/reference_path.yaml @@ -0,0 +1,33 @@ +openapi: 3.1.0 +info: + title: V4 + version: 0.1.0 +servers: + - url: http://localhost +paths: + /pet/{id}: + post: + operationId: operation_post_/pet + parameters: + - name: id + in: path + description: Id of the point + required: true + schema: + $ref: "#/components/schemas/Param" + responses: + "202": + description: Accepted +components: + schemas: + Param: + anyOf: + - type: integer + - type: string + Pet: + type: object + properties: + name: + type: string + owned_by: + type: string diff --git a/openapi-cli/src/test/resources/generators/client/swagger/allOf_path_parameter.yaml b/openapi-cli/src/test/resources/generators/client/swagger/allOf_path_parameter.yaml new file mode 100644 index 000000000..ffb6b4a09 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/allOf_path_parameter.yaml @@ -0,0 +1,48 @@ +openapi: 3.0.1 +info: + title: 'payloadV' + version: 1.0.0 +servers: + - url: localhost:9090/payloadV +paths: + /v1/{id}: + get: + operationId: operationId03 + parameters: + - name: id + description: "id anyOf" + in: path + required: true + schema: + allOf: + - $ref: '#/components/schemas/User' + - type: object + properties: + id: + type: integer + name: + type: string + + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string diff --git a/openapi-cli/src/test/resources/generators/client/swagger/any_type_response.yaml b/openapi-cli/src/test/resources/generators/client/swagger/any_type_response.yaml new file mode 100644 index 000000000..0f2ca6165 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/any_type_response.yaml @@ -0,0 +1,28 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + content: + "*/*": + schema: + type: array + items: + type: string + responses: + '200': + description: Successful operation + content: + '*/*': + example: + summary: Pet Response diff --git a/openapi-cli/src/test/resources/generators/client/swagger/array_response_pdf.yaml b/openapi-cli/src/test/resources/generators/client/swagger/array_response_pdf.yaml new file mode 100644 index 000000000..744024671 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/array_response_pdf.yaml @@ -0,0 +1,93 @@ +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" + content: + '*/*': + schema: + $ref: "#/components/schemas/Pets" + responses: + '200': + description: Successful operation + content: + 'application/pdf': + schema: + type: array + items: + description: "Pet records" + + +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/openapi-cli/src/test/resources/generators/client/swagger/deprecated_functions.yaml b/openapi-cli/src/test/resources/generators/client/swagger/deprecated_functions.yaml index 4819dddf2..b1c64c6f2 100644 --- a/openapi-cli/src/test/resources/generators/client/swagger/deprecated_functions.yaml +++ b/openapi-cli/src/test/resources/generators/client/swagger/deprecated_functions.yaml @@ -47,7 +47,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/client/swagger/display_and_deprecated.yaml b/openapi-cli/src/test/resources/generators/client/swagger/display_and_deprecated.yaml index b176ad363..6d4feba0d 100644 --- a/openapi-cli/src/test/resources/generators/client/swagger/display_and_deprecated.yaml +++ b/openapi-cli/src/test/resources/generators/client/swagger/display_and_deprecated.yaml @@ -49,7 +49,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/client/swagger/empty_object_responnse.yaml b/openapi-cli/src/test/resources/generators/client/swagger/empty_object_responnse.yaml new file mode 100644 index 000000000..58c516737 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/empty_object_responnse.yaml @@ -0,0 +1,90 @@ +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" + content: + '*/*': + schema: + $ref: "#/components/schemas/Pets" + responses: + '200': + description: Successful operation + content: + 'application/json': + schema: + type: object + +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/openapi-cli/src/test/resources/generators/client/swagger/header_integer_signed32.yaml b/openapi-cli/src/test/resources/generators/client/swagger/header_integer_signed32.yaml new file mode 100644 index 000000000..1371ba937 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/header_integer_signed32.yaml @@ -0,0 +1,102 @@ +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: integer + format: int32 + required: true + - in: header + description: Tests header 02 + name: X-Request-Client + schema: + type: array + items: + type: integer + format: int32 + required: true + - in: header + description: Tests header 03 + name: X-Request-Pet + schema: + type: array + items: + $ref: "#/components/schemas/Pet" + required: true + - in: header + description: Tests header 04 + name: X-Request-Header + schema: + type: integer + format: invalid_format + required: false + 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 + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: integer + format: int32 + type: + type: string + securitySchemes: + X-API-KEY: + type: apiKey + in: header + name: X-API-KEY diff --git a/openapi-cli/src/test/resources/generators/client/swagger/integer_request_payload.yaml b/openapi-cli/src/test/resources/generators/client/swagger/integer_request_payload.yaml new file mode 100644 index 000000000..f820945d9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/integer_request_payload.yaml @@ -0,0 +1,61 @@ +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: owners + description: Owners Tag +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + content: + application/json: + schema: + type: integer + format: int32 + required: true + responses: + '201': + description: Pet response + content: + application/json: + schema: + type: integer + format: int32 + /owners: + post: + summary: Create an owner + operationId: createOwner + tags: + - owners + requestBody: + content: + application/json: + schema: + type: integer + format: invalid_format + required: true + responses: + '201': + description: Owner response + content: + application/json: + schema: + type: integer + format: int64 diff --git a/openapi-cli/src/test/resources/generators/client/swagger/integer_signed32_path_parameter.yaml b/openapi-cli/src/test/resources/generators/client/swagger/integer_signed32_path_parameter.yaml new file mode 100644 index 000000000..c69ef5af6 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/integer_signed32_path_parameter.yaml @@ -0,0 +1,33 @@ +openapi: 3.0.1 +info: + title: 'payloadV' + version: 1.0.0 +servers: + - url: localhost:9090/payloadV +paths: + /v1/{id}/payload/{payloadId}: + get: + operationId: operationId01 + description: "op1" + parameters: + - name: id + description: "id value" + in: path + required: true + schema: + type: integer + format: int32 + - name: payloadId + description: "payload id value" + in: path + required: true + schema: + type: integer + format: invalid_format + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string diff --git a/openapi-cli/src/test/resources/generators/client/swagger/map_schema_response.yaml b/openapi-cli/src/test/resources/generators/client/swagger/map_schema_response.yaml new file mode 100644 index 000000000..1d54c89e6 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/map_schema_response.yaml @@ -0,0 +1,97 @@ +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" + content: + '*/*': + schema: + $ref: "#/components/schemas/Pets" + responses: + '200': + description: Successful operation + content: + 'application/json': + schema: + type: object + additionalProperties: + type: object + properties: + code: + type: integer + text: + type: string + +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/openapi-cli/src/test/resources/generators/client/swagger/multipart_binary.yaml b/openapi-cli/src/test/resources/generators/client/swagger/multipart_binary.yaml new file mode 100644 index 000000000..79d119091 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/multipart_binary.yaml @@ -0,0 +1,24 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + description: Pet + content: + multipart/form-data: + schema: + type: string + format: binary + responses: + '201': + description: Null response diff --git a/openapi-cli/src/test/resources/generators/client/swagger/mutipart_formdata_empty.yaml b/openapi-cli/src/test/resources/generators/client/swagger/mutipart_formdata_empty.yaml new file mode 100644 index 000000000..88ca2d5a8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/mutipart_formdata_empty.yaml @@ -0,0 +1,26 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + description: Pet + content: + multipart/form-data: + example: + name: + "Tony" + Age: + "22" + responses: + '201': + description: Null response \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario03_rb.yaml b/openapi-cli/src/test/resources/generators/client/swagger/octet_stream_request_payload.yaml similarity index 79% rename from openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario03_rb.yaml rename to openapi-cli/src/test/resources/generators/client/swagger/octet_stream_request_payload.yaml index 732ee3749..9e5f59d54 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario03_rb.yaml +++ b/openapi-cli/src/test/resources/generators/client/swagger/octet_stream_request_payload.yaml @@ -24,28 +24,31 @@ servers: basePath: default: v2 paths: - /pets: + /user: post: - summary: Add a new pet + summary: Creates a new user. + operationId: "addUser" responses: 200: description: OK requestBody: - description: Optional description in *Markdown* - required: true content: - application/json: - schema: - $ref: '#/components/schemas/Pet' - application/xml: - schema: - $ref: '#/components/schemas/User' - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/PetForm' - text/plain: + application/octet-stream: schema: type: string + /payment: + post: + operationId: "addPayment" + summary: Creates a new payment. + responses: + 200: + description: OK + requestBody: + description: Details of the pet to be purchased + content: + application/octet-stream: + schema: + $ref: '#/components/schemas/Pet' components: schemas: User: diff --git a/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_enum.yaml b/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_enum.yaml new file mode 100644 index 000000000..802c421d8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_enum.yaml @@ -0,0 +1,169 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: + default: live + enum: + - scheduled + - live + - upcoming + type: string + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + default: "available" + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + required: true + - description: Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + in: header + name: X-Date-Format + schema: + enum: + - UTC + - LOCAL + - OFFSET + - EPOCH + - LEET + - description: Time Zones of attendees + in: header + required: true + name: X-Time-Zones + schema: + type: array + items: + enum: + - IST + - GMT + - UTC + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/RoomNo' + - $ref: "#/components/parameters/responseFormat" + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + RoomNo: + default: "R5" + enum: + - R1 + - R3 + - R5 + type: string + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_nullable_enums.yaml b/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_nullable_enums.yaml new file mode 100644 index 000000000..c616e6895 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/parameters_with_nullable_enums.yaml @@ -0,0 +1,153 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: +# default: live + enum: + - scheduled + - live + - upcoming + - null + type: string + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + - null + - description: Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + in: header + name: X-Date-Format + schema: + enum: + - UTC + - LOCAL + - OFFSET + - EPOCH + - LEET + - null + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/RoomNo' + - $ref: "#/components/parameters/responseFormat" + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + - null + type: string + schemas: + RoomNo: +# How can we address when default value is there in a reusable enum + default: R5 + enum: + - R1 + - R3 + - R5 + - null + type: string + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable.yaml b/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable.yaml new file mode 100644 index 000000000..804a3b5cc --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable.yaml @@ -0,0 +1,97 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + - null + nullable: true + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable_enum.yaml b/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable_enum.yaml new file mode 100644 index 000000000..804a3b5cc --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/path_param_nullable_enum.yaml @@ -0,0 +1,97 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + - null + nullable: true + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/client/swagger/query_param_with_integer_value.yaml b/openapi-cli/src/test/resources/generators/client/swagger/query_param_with_integer_value.yaml new file mode 100644 index 000000000..c40ff3882 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/query_param_with_integer_value.yaml @@ -0,0 +1,98 @@ +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: + type: integer + format: int32 + x-ballerina-display: + label: Latitude + - description: "Longtitude" + in: query + name: lon + required: false + schema: + type: integer + format: int32 + x-ballerina-display: + label: Longtitude + - description: "test" + in: query + name: exclude + required: false + schema: + type: integer + format: invalid_format + default: 100 + x-ballerina-display: + label: Exclude + - description: 'units' + in: query + name: units + required: true + schema: + type: integer + format: int64 + default: 12 + x-ballerina-display: + label: Units + x-ballerina-display: + label: "Weather Forecast" + responses: + 200: + description: Successful response + 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" +components: + schemas: + WeatherForecast: + type: object + properties: + lat: + type: number + lon: + type: number + securitySchemes: + app_id: + type: apiKey + description: API key. + name: appid + in: query diff --git a/openapi-cli/src/test/resources/generators/client/swagger/request_body_has_object_content_without_property.yaml b/openapi-cli/src/test/resources/generators/client/swagger/request_body_has_object_content_without_property.yaml new file mode 100644 index 000000000..0700eb928 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/request_body_has_object_content_without_property.yaml @@ -0,0 +1,149 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + post: + summary: The Request body is with reference to the reusable requestBody with content type has object without properties + operationId: op01 + requestBody: + content: + application/json: + schema: + type: object + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + put: + summary: Request body has object schema content without the properties field + operationId: op02 + requestBody: + $ref: "#/components/requestBodies/PetBody" + + responses: + "200": + description: Ok + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + /greeting02: + post: + summary: RequestBody has object content without properties with application/xml + operationId: op03 + requestBody: + content: + application/xml: + schema: + type: object + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + put: + summary: RequestBody has object content without properties with vendor-specific media type vnd.petstore.v3.diff+json + operationId: op04 + requestBody: + content: + application/vnd.petstore.v3.diff+json: + schema: + type: object + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + /greeting03: + put: + summary: Request body has properties with {} value + operationId: op05 + requestBody: + content: + application/json: + schema: + type: object + properties: {} + + responses: + "200": + description: Ok + post: + summary: Request body has non-standard media type application/zip with object content without properties + operationId: op06 + requestBody: + content: + application/zip: + schema: + type: object + responses: + "200": + description: Ok +components: + requestBodies: + PetBody: + description: A JSON object containing pet information + required: true + content: + application/json: + schema: + type: object + schemas: + Street: + type: object + properties: + laneNo: + oneOf: + - type: string + - type: integer + laneType: + anyOf: + - type: string + - type: integer + Address: + allOf: + - $ref: "#/components/schemas/Street" + - type: object + properties: + no: + type: integer + Person: + type: object + required: + - id + properties: + name: + type: string + hobby: + type: array + items: + type: string + id: + type: integer + maximum: 5 + salary: + type: number + format: float + net: + type: number + count: + type: integer + format: int32 + address: + $ref: "#/components/schemas/Address" diff --git a/openapi-cli/src/test/resources/generators/client/swagger/request_body_with_ref.yaml b/openapi-cli/src/test/resources/generators/client/swagger/request_body_with_ref.yaml new file mode 100644 index 000000000..8de6c204f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/request_body_with_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/openapi-cli/src/test/resources/generators/client/swagger/request_body_without_schema.yaml b/openapi-cli/src/test/resources/generators/client/swagger/request_body_without_schema.yaml index 27106f152..9451e4d9c 100644 --- a/openapi-cli/src/test/resources/generators/client/swagger/request_body_without_schema.yaml +++ b/openapi-cli/src/test/resources/generators/client/swagger/request_body_without_schema.yaml @@ -46,7 +46,6 @@ paths: required: false schema: type: integer - format: int32 requestBody: description: Pet content: diff --git a/openapi-cli/src/test/resources/generators/client/swagger/return_type/no_response.yaml b/openapi-cli/src/test/resources/generators/client/swagger/return_type/no_response.yaml new file mode 100644 index 000000000..7e1064196 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/return_type/no_response.yaml @@ -0,0 +1,26 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://localhost:9090/petstore/v1 +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: {} diff --git a/openapi-cli/src/test/resources/generators/client/swagger/return_type/response_with_only_additional_schema.yaml b/openapi-cli/src/test/resources/generators/client/swagger/return_type/response_with_only_additional_schema.yaml new file mode 100644 index 000000000..3d250b376 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/return_type/response_with_only_additional_schema.yaml @@ -0,0 +1,64 @@ +openapi: 3.1.0 +info: + title: Swagger Petstore - OpenAPI 3.1 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.1 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + parameters: [ ] + responses: + "200": + description: "successful operation" + content: + application/json: + schema: + additionalProperties: + type: "integer" + format: "int32" +components: + schemas: + Category: + type: object + properties: + name: + type: + - string + nullable: true + Pet: + required: + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: + - string + - "null" + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + - null \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/client/swagger/union_path_parameter.yaml b/openapi-cli/src/test/resources/generators/client/swagger/union_path_parameter.yaml new file mode 100644 index 000000000..921c7bfb2 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/union_path_parameter.yaml @@ -0,0 +1,44 @@ +openapi: 3.0.1 +info: + title: 'payloadV' + version: 1.0.0 +servers: + - url: localhost:9090/payloadV +paths: + /v1/{id}: + get: + operationId: operationId03 + parameters: + - name: id + description: "id anyOf" + in: path + required: true + schema: + anyOf: + - type: integer + - type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + post: + operationId: post + parameters: + - name: id + description: "id oneOf" + in: path + required: true + schema: + oneOf: + - type: integer + - type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string diff --git a/openapi-cli/src/test/resources/generators/client/swagger/unsupported_request_body.yaml b/openapi-cli/src/test/resources/generators/client/swagger/unsupported_request_body.yaml index 59cf8754d..d857e0775 100644 --- a/openapi-cli/src/test/resources/generators/client/swagger/unsupported_request_body.yaml +++ b/openapi-cli/src/test/resources/generators/client/swagger/unsupported_request_body.yaml @@ -11,28 +11,6 @@ info: version: '2020-08-27' x-stripeSpecFilename: spec3 paths: - "/v1/payment_methods/{payment_method}": - get: - description: "

Retrieves a PaymentMethod object.

" - operationId: GetPaymentMethodsPaymentMethod - tags: - - "Payment_Methods" - parameters: - - in: path - name: payment_method - description: Payment Method - required: true - schema: - maxLength: 5000 - type: string - style: simple - - responses: - '200': - content: - application/json: - schema: {} - description: Successful response. "/v1/customer/{customer}": post: description: "

Creates a new customer object.

" diff --git a/openapi-cli/src/test/resources/generators/client/swagger/unsupported_text_media_type.yaml b/openapi-cli/src/test/resources/generators/client/swagger/unsupported_text_media_type.yaml new file mode 100644 index 000000000..d6d9a8f93 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/unsupported_text_media_type.yaml @@ -0,0 +1,62 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + content: + text/xxx: + example: + name : "Tommy" + responses: + '200': + description: Response of create pet + content: + text/xxx: + schema: {} +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/openapi-cli/src/test/resources/generators/client/swagger/vendor_specific_with_subtype.yaml b/openapi-cli/src/test/resources/generators/client/swagger/vendor_specific_with_subtype.yaml new file mode 100644 index 000000000..b50ffc525 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/client/swagger/vendor_specific_with_subtype.yaml @@ -0,0 +1,72 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + content: + application/vnd.petstore.v3.diff+json: + schema: + $ref: "#/components/schemas/Pet" + responses: + '200': + description: List of existing pets + content: + application/vnd.petstore.v3.diff+json: + schema: + $ref: "#/components/schemas/Pets" + /v0/pets: + post: + summary: Create a pet + operationId: createPetV0 + requestBody: + content: + application/vnd.petstore.v3.diff+xml: + schema: + $ref: "#/components/schemas/Pet" + responses: + '200': + description: List of existing pets + content: + application/vnd.petstore.v3.diff+xml: + schema: + $ref: "#/components/schemas/Pets" +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/openapi-cli/src/test/resources/generators/client/utils/swagger/multipart_formdata.yaml b/openapi-cli/src/test/resources/generators/client/utils/swagger/multipart_formdata.yaml index 8c4fd3d35..4f655f31d 100644 --- a/openapi-cli/src/test/resources/generators/client/utils/swagger/multipart_formdata.yaml +++ b/openapi-cli/src/test/resources/generators/client/utils/swagger/multipart_formdata.yaml @@ -40,3 +40,24 @@ paths: responses: '201': description: Null response + /user: + post: + summary: Create an user + operationId: createUser + requestBody: + description: User + content: + multipart/form-data: + encoding: { } + schema: + required: + - File + type: object + properties: + File: + type: string + format: binary + required: false + responses: + '201': + description: Null response diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/adyen_accountservice.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/adyen_accountservice.yaml new file mode 100644 index 000000000..c5ac3dc8b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/adyen_accountservice.yaml @@ -0,0 +1,3511 @@ +openapi: 3.1.0 +servers: + - url: https://cal-test.adyen.com/cal/services/Account/v3 +info: + contact: + name: Adyen Developer Experience team + url: https://github.com/Adyen/adyen-openapi + x-twitter: Adyen + description: |- + This API is used for the classic integration. If you are just starting your implementation, refer to our [new integration guide](https://docs.adyen.com/marketplaces-and-platforms) instead. + + The Account API provides endpoints for managing account-related entities on your platform. These related entities include account holders, accounts, bank accounts, shareholders, and verification-related documents. The management operations include actions such as creation, retrieval, updating, and deletion of them. + + For more information, refer to our [documentation](https://docs.adyen.com/marketplaces-and-platforms/classic). + ## Authentication + Your Adyen contact will provide your API credential and an API key. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: + + ``` + curl + -H "Content-Type: application/json" \ + -H "X-API-Key: YOUR_API_KEY" \ + ... + ``` + + Alternatively, you can use the username and password to connect to the API using basic authentication. For example: + + ``` + curl + -U "ws@MarketPlace.YOUR_PLATFORM_ACCOUNT":"YOUR_WS_PASSWORD" \ + -H "Content-Type: application/json" \ + ... + ``` + When going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). + + ## Versioning + The Account API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: "vXX", where XX is the version number. + + For example: + ``` + https://cal-test.adyen.com/cal/services/Account/v3/createAccountHolder + ``` + termsOfService: https://www.adyen.com/legal/terms-and-conditions + title: Account API + version: "3" + x-apisguru-categories: + - payment + x-logo: + url: https://twitter.com/Adyen/profile_image?size=original + x-origin: + - format: openapi + url: https://raw.githubusercontent.com/Adyen/adyen-openapi/main/json/AccountService-v3.json + version: "3.1" + x-preferred: false + x-providerName: adyen.com + x-publicVersion: true + x-serviceName: AccountService + x-timestamp: 2023-05-30T15:27:20Z +tags: + - name: Account holders + - name: Verification + - name: Accounts +paths: + /closeAccount: + post: + description: Closes an account. If an account is closed, you cannot process transactions, pay out its funds, or reopen it. If payments are made to a closed account, the payments are sent to your liable account. + operationId: post-closeAccount + requestBody: + content: + application/json: + examples: + closeAccount: + $ref: "#/components/examples/post-closeAccount-closeAccount" + schema: + $ref: "#/components/schemas/CloseAccountRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CloseAccountResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/CloseAccountResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Close an account + tags: + - Accounts + x-groupName: Accounts + x-methodName: closeAccount + x-sortIndex: 3 + /closeAccountHolder: + post: + description: Changes the [status of an account holder](https://docs.adyen.com/marketplaces-and-platforms/classic/account-holders-and-accounts#account-holder-statuses) to **Closed**. This state is final. If an account holder is closed, you can't process transactions, pay out funds, or reopen it. If payments are made to an account of an account holder with a **Closed** [`status`](https://docs.adyen.com/api-explorer/#/Account/latest/post/getAccountHolder__resParam_verification-accountHolder-checks-status), the payments are sent to your liable account. + operationId: post-closeAccountHolder + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-closeAccountHolder-basic" + schema: + $ref: "#/components/schemas/CloseAccountHolderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CloseAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/CloseAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Close an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: closeAccountHolder + x-sortIndex: 7 + /createAccount: + post: + description: Creates an account under an account holder. An account holder can have [multiple accounts](https://docs.adyen.com/marketplaces-and-platforms/classic/account-holders-and-accounts#create-additional-accounts). + operationId: post-createAccount + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-createAccount-basic" + schema: + $ref: "#/components/schemas/CreateAccountRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateAccountResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateAccountResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Create an account + tags: + - Accounts + x-groupName: Accounts + x-methodName: createAccount + x-sortIndex: 1 + /createAccountHolder: + post: + description: Creates an account holder that [represents the sub-merchant's entity](https://docs.adyen.com/marketplaces-and-platforms/classic/account-structure#your-platform) in your platform. The details that you need to provide in the request depend on the sub-merchant's legal entity type. For more information, refer to [Account holder and accounts](https://docs.adyen.com/marketplaces-and-platforms/classic/account-holders-and-accounts#legal-entity-types). + operationId: post-createAccountHolder + requestBody: + content: + application/json: + examples: + business: + $ref: "#/components/examples/post-createAccountHolder-business" + individual: + $ref: "#/components/examples/post-createAccountHolder-individual" + schema: + $ref: "#/components/schemas/CreateAccountHolderRequest" + responses: + "200": + content: + application/json: + examples: + business: + $ref: "#/components/examples/post-createAccountHolder-business-200" + individual: + $ref: "#/components/examples/post-createAccountHolder-individual-200" + schema: + $ref: "#/components/schemas/CreateAccountHolderResponse" + description: OK - the request has succeeded. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/post-createAccountHolder-generic-401" + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + examples: + business: + $ref: "#/components/examples/post-createAccountHolder-business-422" + individual: + $ref: "#/components/examples/post-createAccountHolder-individual-422" + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/post-createAccountHolder-generic-500" + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Create an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: createAccountHolder + x-sortIndex: 1 + /deleteBankAccounts: + post: + description: "Deletes bank accounts associated with an account holder. " + operationId: post-deleteBankAccounts + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-deleteBankAccounts-basic" + schema: + $ref: "#/components/schemas/DeleteBankAccountRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Delete bank accounts + tags: + - Verification + x-groupName: Verification + x-methodName: deleteBankAccounts + x-sortIndex: 4 + /deleteLegalArrangements: + post: + description: Deletes legal arrangements and/or legal arrangement entities associated with an account holder. + operationId: post-deleteLegalArrangements + requestBody: + content: + application/json: + examples: + arrangements: + $ref: "#/components/examples/post-deleteLegalArrangements-arrangements" + entities: + $ref: "#/components/examples/post-deleteLegalArrangements-entities" + schema: + $ref: "#/components/schemas/DeleteLegalArrangementRequest" + responses: + "200": + content: + application/json: + examples: + arrangements: + $ref: "#/components/examples/post-deleteLegalArrangements-arrangements-200" + entities: + $ref: "#/components/examples/post-deleteLegalArrangements-entities-200" + schema: + $ref: "#/components/schemas/GenericResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + arrangements: + $ref: "#/components/examples/post-deleteLegalArrangements-arrangements-400" + entities: + $ref: "#/components/examples/post-deleteLegalArrangements-entities-400" + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Delete legal arrangements + tags: + - Verification + x-groupName: Verification + x-methodName: deleteLegalArrangements + x-sortIndex: 6 + /deleteShareholders: + post: + description: Deletes shareholders associated with an account holder. + operationId: post-deleteShareholders + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-deleteShareholders-basic" + schema: + $ref: "#/components/schemas/DeleteShareholderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Delete shareholders + tags: + - Verification + x-groupName: Verification + x-methodName: deleteShareholders + x-sortIndex: 7 + /deleteSignatories: + post: + description: Deletes signatories associated with an account holder. + operationId: post-deleteSignatories + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DeleteSignatoriesRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GenericResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Delete signatories + tags: + - Verification + x-groupName: Verification + x-methodName: deleteSignatories + x-sortIndex: 8 + /getAccountHolder: + post: + description: Returns the details of an account holder. + operationId: post-getAccountHolder + requestBody: + content: + application/json: + examples: + accountCode: + $ref: "#/components/examples/post-getAccountHolder-accountCode" + accountHolderCode: + $ref: "#/components/examples/post-getAccountHolder-accountHolderCode" + schema: + $ref: "#/components/schemas/GetAccountHolderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GetAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Get an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: getAccountHolder + x-sortIndex: 2 + /getTaxForm: + post: + description: Generates a tax form for account holders operating in the US. For more information, refer to [Providing tax forms](https://docs.adyen.com/marketplaces-and-platforms/classic/tax-forms). + operationId: post-getTaxForm + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-getTaxForm-basic" + schema: + $ref: "#/components/schemas/GetTaxFormRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetTaxFormResponse" + description: OK - the request has succeeded. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Get a tax form + tags: + - Account holders + x-groupName: Account holders + x-methodName: getTaxForm + x-sortIndex: 8 + /getUploadedDocuments: + post: + description: | + Returns documents that were previously uploaded for an account holder. Adyen uses the documents during the [verification process](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process). + operationId: post-getUploadedDocuments + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-getUploadedDocuments-basic" + schema: + $ref: "#/components/schemas/GetUploadedDocumentsRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetUploadedDocumentsResponse" + description: OK - the request has succeeded. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Get documents + tags: + - Verification + x-groupName: Verification + x-methodName: getUploadedDocuments + x-sortIndex: 2 + /suspendAccountHolder: + post: + description: Changes the [status of an account holder](https://docs.adyen.com/marketplaces-and-platforms/classic/account-holders-and-accounts#account-holder-statuses) to **Suspended**. + operationId: post-suspendAccountHolder + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-suspendAccountHolder-basic" + schema: + $ref: "#/components/schemas/SuspendAccountHolderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SuspendAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/SuspendAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Suspend an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: suspendAccountHolder + x-sortIndex: 5 + /unSuspendAccountHolder: + post: + description: |- + Changes the [status of an account holder](https://docs.adyen.com/marketplaces-and-platforms/classic/account-holders-and-accounts#account-holder-statuses) from **Suspended** to **Inactive**. + Account holders can have a **Suspended** [`status`](https://docs.adyen.com/api-explorer/#/Account/latest/post/getAccountHolder__resParam_verification-accountHolder-checks-status) if you suspend them through the [`/suspendAccountHolder`](https://docs.adyen.com/api-explorer/#/Account/v5/post/suspendAccountHolder) endpoint or if a verification deadline expires. + + You can only unsuspend account holders if they do not have verification checks with a **FAILED** [`status`](https://docs.adyen.com/api-explorer/#/Account/latest/post/getAccountHolder__resParam_verification-accountHolder-checks-status). + operationId: post-unSuspendAccountHolder + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-unSuspendAccountHolder-basic" + schema: + $ref: "#/components/schemas/UnSuspendAccountHolderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UnSuspendAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/UnSuspendAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Unsuspend an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: unSuspendAccountHolder + x-sortIndex: 6 + /updateAccount: + post: + description: Updates the description or payout schedule of an account. + operationId: post-updateAccount + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-updateAccount-basic" + schema: + $ref: "#/components/schemas/UpdateAccountRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Update an account + tags: + - Accounts + x-groupName: Accounts + x-methodName: updateAccount + x-sortIndex: 2 + /updateAccountHolder: + post: + description: |+ + Updates the `accountHolderDetails` and `processingTier` of an account holder, and adds bank accounts and shareholders. + + When updating `accountHolderDetails`, parameters that are not included in the request are left unchanged except for the following object: + + * `metadata`: Updating the metadata replaces the entire object. This means that to update an existing key-value pair, you must provide the changes, as well as other existing key-value pairs. + + When updating any field in the following objects, you must submit all the fields required for validation: + + * `address` + + * `fullPhoneNumber` + + * `bankAccountDetails.BankAccountDetail` + + * `businessDetails.shareholders.ShareholderContact` + + For example, to update the `address.postalCode`, you must also submit the `address.country`, `.city`, `.street`, `.postalCode`, and possibly `.stateOrProvince` so that the address can be validated. + + To add a bank account or shareholder, provide the bank account or shareholder details without a `bankAccountUUID` or a `shareholderCode`. + + operationId: post-updateAccountHolder + requestBody: + content: + application/json: + examples: + addShareholders: + $ref: "#/components/examples/post-updateAccountHolder-addShareholders" + bankAccountDetails: + $ref: "#/components/examples/post-updateAccountHolder-bankAccountDetails" + businessDetails: + $ref: "#/components/examples/post-updateAccountHolder-businessDetails" + general: + $ref: "#/components/examples/post-updateAccountHolder-general" + schema: + $ref: "#/components/schemas/UpdateAccountHolderRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Update an account holder + tags: + - Account holders + x-groupName: Account holders + x-methodName: updateAccountHolder + x-sortIndex: 3 + /updateAccountHolderState: + post: + description: Disables or enables the processing or payout state of an account holder. + operationId: post-updateAccountHolderState + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-updateAccountHolderState-basic" + schema: + $ref: "#/components/schemas/UpdateAccountHolderStateRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetAccountHolderStatusResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/GetAccountHolderStatusResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Update payout or processing state + tags: + - Account holders + x-groupName: Account holders + x-methodName: updateAccountHolderState + x-sortIndex: 4 + /uploadDocument: + post: + description: Uploads a document for an account holder. Adyen uses the documents during the [verification process](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process). + operationId: post-uploadDocument + requestBody: + content: + application/json: + examples: + basic: + $ref: "#/components/examples/post-uploadDocument-basic" + schema: + $ref: "#/components/schemas/UploadDocumentRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountHolderResponse" + description: OK - the request has succeeded. + "202": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateAccountHolderResponse" + description: Accepted - the request has been accepted for processing, but the processing has not been completed. + "400": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-400" + schema: + $ref: "#/components/schemas/ServiceError" + description: Bad Request - a problem reading or understanding the request. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unauthorized - authentication required. + "403": + content: + application/json: + examples: + generic: + $ref: "#/components/examples/generic-403" + schema: + $ref: "#/components/schemas/ServiceError" + description: Forbidden - insufficient permissions to process the request. + "422": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Unprocessable Entity - a request validation error. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/ServiceError" + description: Internal Server Error - the server could not process the request. + security: + - BasicAuth: [] + - ApiKeyAuth: [] + summary: Upload a document + tags: + - Verification + x-groupName: Verification + x-methodName: uploadDocument + x-sortIndex: 1 +components: + examples: + generic-400: + summary: Response code 400. Bad Request. + value: + errorCode: "702" + errorType: validation + message: "Unexpected input: I" + status: 400 + generic-403: + summary: Response code 401. Forbidden. + value: + errorCode: 10_003 + errorType: security + message: Failed to authorize user + status: 403 + post-closeAccount-closeAccount: + summary: Close an account + value: + accountCode: CODE_OF_ACCOUNT + post-closeAccountHolder-basic: + summary: Close an account holder + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + post-createAccount-basic: + summary: Add an account to an account holder + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + post-createAccountHolder-business: + summary: Create a business account holder + value: + accountHolderCode: GENERATE_CODE + accountHolderDetails: + businessDetails: + doingBusinessAs: Real Good Restaurant + legalBusinessName: Real Good Restaurant Inc. + shareholders: + - ShareholderContact: + name: + firstName: John + lastName: Carpenter + email: test@adyen.com + webAddress: https://www.your-website.com + legalEntity: Business + post-createAccountHolder-business-200: + summary: Response code 200. Success. + value: + accountCode: "8816080397613522" + accountHolderCode: GENERATE_CODE + accountHolderDetails: + address: + country: US + bankAccountDetails: [] + email: tim@green.com + individualDetails: + name: + firstName: Tim + lastName: Green + merchantCategoryCode: "7999" + payoutMethods: [] + webAddress: null + accountHolderStatus: + events: [] + payoutState: + allowPayout: false + disabled: false + processingState: + disabled: false + processedFrom: + currency: USD + value: 0 + processedTo: + currency: USD + value: 9999 + tierNumber: 0 + status: Active + invalidFields: [] + legalEntity: Individual + pspReference: "8816080397613514" + verification: + accountHolder: + checks: + - requiredFields: + - AccountHolderDetails.IndividualDetails.PersonalData.personalData + - AccountHolderDetails.Address.city + - AccountHolderDetails.Address.houseNumberOrName + - AccountHolderDetails.Address.postalCode + - AccountHolderDetails.Address.street + - AccountHolderDetails.IndividualDetails.PersonalData.idNumber + - AccountHolderDetails.PhoneNumber.phoneNumber + status: AWAITING_DATA + type: IDENTITY_VERIFICATION + - requiredFields: + - AccountHolderDetails.BankAccountDetails.bankAccount + status: AWAITING_DATA + type: PAYOUT_METHOD_VERIFICATION + post-createAccountHolder-business-422: + summary: Response code 422. Unprocessable Entity. + value: + invalidFields: + - errorCode: 23 + errorDescription: Account holder code does not exists or invalid + fieldType: + field: accountHolderCode + fieldName: accountHolderCode + pspReference: "8816080407386622" + post-createAccountHolder-generic-401: + summary: Response code 401. Unauthorized. + value: + errorCode: "000" + errorType: security + message: HTTP Status Response - Unauthorized + status: 401 + post-createAccountHolder-generic-500: + summary: Response code 500. Internal Server Error. + value: + errorCode: "701" + errorType: internal + message: Internal Error in createAccountHolder 991608040809302G + status: 500 + post-createAccountHolder-individual: + summary: Create an individual account holder + value: + accountHolderCode: GENERATE_CODE + accountHolderDetails: + email: tim@green.com + individualDetails: + name: + firstName: Tim + lastName: Green + webAddress: https://www.your-website.com + legalEntity: Individual + post-createAccountHolder-individual-200: + summary: Response code 200. Success. + value: + accountCode: "8516080413108724" + accountHolderCode: GENERATE_CODE + accountHolderDetails: + address: + country: US + bankAccountDetails: [] + email: tim@green.com + individualDetails: + name: + firstName: Tim + lastName: Green + merchantCategoryCode: "7999" + payoutMethods: [] + webAddress: null + accountHolderStatus: + events: [] + payoutState: + allowPayout: false + disabled: false + processingState: + disabled: false + processedFrom: + currency: USD + value: 0 + processedTo: + currency: USD + value: 9999 + tierNumber: 0 + status: Active + invalidFields: [] + legalEntity: Individual + pspReference: "8516080413108716" + verification: + accountHolder: + checks: + - requiredFields: + - AccountHolderDetails.Address.city + - AccountHolderDetails.Address.houseNumberOrName + - AccountHolderDetails.Address.postalCode + - AccountHolderDetails.Address.street + - AccountHolderDetails.IndividualDetails.PersonalData.idNumber + - AccountHolderDetails.PhoneNumber.phoneNumber + - AccountHolderDetails.IndividualDetails.PersonalData.personalData + status: AWAITING_DATA + type: IDENTITY_VERIFICATION + - requiredFields: + - AccountHolderDetails.BankAccountDetails.bankAccount + status: AWAITING_DATA + type: PAYOUT_METHOD_VERIFICATION + post-createAccountHolder-individual-422: + summary: Response code 422. Unprocessable Entity. + value: + invalidFields: + - errorCode: 21 + errorDescription: Account description ' SpecialCharactersIncluded' is not valid + fieldType: + field: description + fieldName: description + pspReference: "8816080421120908" + post-deleteBankAccounts-basic: + summary: Delete bank accounts + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + bankAccountUUIDs: + - eeb6ed22-3bae-483c-83b9-bc2097a75d40 + post-deleteLegalArrangements-arrangements: + description: Example request for deleting legal arrangements + summary: Delete legal arrangements + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + legalArrangements: + - legalArrangementCode: cdf92f5a-a114-4ce6-8f19-c3f6ec83141c + post-deleteLegalArrangements-arrangements-200: + summary: Legal arrangement deleted + value: + invalidFields: [] + pspReference: "8816080397613514" + post-deleteLegalArrangements-arrangements-400: + summary: Response code 400. Bad Request. + value: + invalidFields: + - errorCode: 34 + errorDescription: An invalid legalArrangementCode code is provided for value 'cdf92f5a-a114-4ce6-8f19-c3f6ec83141c' + fieldType: + field: AccountHolderDetails.LegalArrangements.legalArrangementCode + fieldName: legalArrangementCode + pspReference: "9916613322577326" + post-deleteLegalArrangements-entities: + description: Example request for deleting legal arrangement entities + summary: Delete legal arrangement entities + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + legalArrangements: + - legalArrangementCode: cdf92f5a-a114-4ce6-8f19-c3f6ec83141c + legalArrangementEntityCodes: + - 755881d3-d6b0-4b34-8ace-1caceb8add63 + post-deleteLegalArrangements-entities-200: + summary: Legal arrangement entities deleted + value: + invalidFields: [] + pspReference: "8816080397613514" + post-deleteLegalArrangements-entities-400: + summary: Response code 400. Bad Request. + value: + invalidFields: + - errorCode: 34 + errorDescription: An invalid legalArrangementEntityCode code is provided for value 'c92bb932-4867-4cef-bf9d-4ecde37745cf' + fieldType: + field: AccountHolderDetails.LegalArrangements.LegalArrangementsEntities.legalArrangementEntityCode + fieldName: legalArrangementEntityCode + pspReference: "9916613324987358" + post-deleteShareholders-basic: + summary: Delete shareholders + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + shareholderCodes: + - 9188218c-576e-4cbe-8e86-72722f453920 + post-getAccountHolder-accountCode: + summary: Get an account holder + value: + accountCode: CODE_OF_ACCOUNT + post-getAccountHolder-accountHolderCode: + summary: Get an account holder for the account + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + post-getTaxForm-basic: + summary: Get a tax form + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + formType: 1099-K + year: 2020 + post-getUploadedDocuments-basic: + summary: Get uploaded documents + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + bankAccountUUID: EXAMPLE_UUID + post-suspendAccountHolder-basic: + summary: Suspend an account holder + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + post-unSuspendAccountHolder-basic: + summary: Unsuspend an account holder + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + post-updateAccount-basic: + summary: Set a payout schedule + value: + accountCode: CODE_OF_ACCOUNT + payoutSchedule: + action: CLOSE + schedule: WEEKLY + post-updateAccountHolder-addShareholders: + summary: Add shareholders + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + accountHolderDetails: + bankAccountDetails: [] + businessDetails: + legalBusinessName: legalBusinessName + shareholders: + - ShareholderContact: + email: testEmail@gmail.com + personalData: + idNumber: "12345" + taxId: taxid + post-updateAccountHolder-bankAccountDetails: + summary: Update bank account details + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + accountHolderDetails: + bankAccountDetails: + - BankAccountDetail: + accountNumber: "1678116852" + branchCode: "053101273" + countryCode: US + currencyCode: USD + ownerCity: Springfield + ownerCountryCode: US + ownerHouseNumberOrName: "100" + ownerName: Tim Green + ownerPostalCode: "02894" + ownerState: AZ + ownerStreet: Main Street + email: tim@green.com + individualDetails: + name: + firstName: Tim + lastName: Green + createDefaultAccount: "true" + legalEntity: Individual + post-updateAccountHolder-businessDetails: + summary: Update business details + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + accountHolderDetails: + bankAccountDetails: [] + businessDetails: + doingBusinessAs: Test company B.V. + legalBusinessName: Test company + shareholders: + - ShareholderContact: + address: + city: Amsterdam + country: NL + houseNumberOrName: "1" + postalCode: 1111AA + stateOrProvince: NH + street: Teststreet + email: testShareholder@adyen.com + name: + firstName: TestFirstName + lastName: TestLastName + taxId: BV123456789 + email: test@adyen.com + phoneNumber: + phoneCountryCode: NL + phoneNumber: "0612345678" + phoneType: Mobile + webAddress: http://www.accountholderwebsite.com + post-updateAccountHolder-general: + summary: Update account holder details + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + accountHolderDetails: + address: + city: Amsterdam + country: NL + postalCode: "12345" + stateOrProvince: NH + street: Teststreet 1 + bankAccountDetails: [] + email: test@adyen.com + individualDetails: + name: + firstName: First name + lastName: Last Name + personalData: + dateOfBirth: 1970-01-01 + idNumber: "1234567890" + nationality: NL + merchantCategoryCode: "7999" + phoneNumber: + phoneCountryCode: NL + phoneNumber: "0612345678" + phoneType: Mobile + webAddress: http://www.accountholderwebsite.com + post-updateAccountHolderState-basic: + summary: Update account holder state + value: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + disable: true + reason: test reason payout + stateType: Payout + post-uploadDocument-basic: + summary: Upload a document + value: + documentContent: dGVzdCBkb2N1bWVudCBjb250ZW50 + documentDetail: + accountHolderCode: CODE_OF_ACCOUNT_HOLDER + description: test passport description + documentType: PASSPORT + filename: passport.png + schemas: + Account: + properties: + accountCode: + description: The code of the account. + type: string + beneficiaryAccount: + description: The beneficiary of the account. + type: string + beneficiaryMerchantReference: + description: The reason that a beneficiary has been set up for this account. This may have been supplied during the setup of a beneficiary at the discretion of the executing user. + type: string + payoutSchedule: + $ref: "#/components/schemas/PayoutScheduleResponse" + description: The account's payout schedule. + type: object + AccountEvent: + properties: + event: + description: |- + The event. + >Permitted values: `InactivateAccount`, `RefundNotPaidOutTransfers`. + For more information, refer to [Verification checks](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process). + enum: + - InactivateAccount + - RefundNotPaidOutTransfers + type: string + executionDate: + description: The date on which the event will take place. + format: date-time + type: string + reason: + description: The reason why this event has been created. + type: string + type: object + AccountEventWrapper: + properties: + AccountEvent: + $ref: "#/components/schemas/AccountEvent" + AccountHolderDetails: + properties: + address: + $ref: "#/components/schemas/ViasAddress" + description: The address of the account holder. + bankAccountDetails: + description: Array of bank accounts associated with the account holder. For details about the required `bankAccountDetail` fields, see [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information). + items: + $ref: "#/components/schemas/BankAccountDetailWrapper" + type: array + businessDetails: + $ref: "#/components/schemas/BusinessDetails" + description: |- + Details about the business or nonprofit account holder. + Required when creating an account holder with `legalEntity` **Business** or **NonProfit**. + email: + description: The email address of the account holder. + type: string + fullPhoneNumber: + description: |- + The phone number of the account holder provided as a single string. It will be handled as a landline phone. + **Examples:** "0031 6 11 22 33 44", "+316/1122-3344", "(0031) 611223344" + type: string + individualDetails: + $ref: "#/components/schemas/IndividualDetails" + description: | + Details about the individual account holder. + Required when creating an account holder with `legalEntity` **Individual**. + lastReviewDate: + description: Date when you last reviewed the account holder's information, in ISO-8601 YYYY-MM-DD format. For example, **2020-01-31**. + type: string + merchantCategoryCode: + description: |- + The Merchant Category Code of the account holder. + > If not specified in the request, this will be derived from the platform account (which is configured by Adyen). + type: string + metadata: + additionalProperties: + type: string + description: |- + A set of key and value pairs for general use by the account holder or merchant. + The keys do not have specific names and may be used for storing miscellaneous data as desired. + > The values being stored have a maximum length of eighty (80) characters and will be truncated if necessary. + > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + type: object + principalBusinessAddress: + $ref: "#/components/schemas/ViasAddress" + description: The principal business address of the account holder. + webAddress: + description: The URL of the website of the account holder. + type: string + required: + - address + type: object + AccountHolderStatus: + properties: + events: + description: A list of events scheduled for the account holder. + items: + $ref: "#/components/schemas/AccountEventWrapper" + type: array + payoutState: + $ref: "#/components/schemas/AccountPayoutState" + description: The payout state of the account holder. + processingState: + $ref: "#/components/schemas/AccountProcessingState" + description: The processing state of the account holder. + status: + description: |- + The status of the account holder. + >Permitted values: `Active`, `Inactive`, `Suspended`, `Closed`. + enum: + - Active + - Closed + - Inactive + - Suspended + type: string + statusReason: + description: The reason why the status was assigned to the account holder. + type: string + required: + - status + type: object + AccountPayoutState: + properties: + allowPayout: + description: Indicates whether payouts are allowed. This field is the overarching payout status, and is the aggregate of multiple conditions (e.g., KYC status, disabled flag, etc). If this field is false, no payouts will be permitted for any of the account holder's accounts. If this field is true, payouts will be permitted for any of the account holder's accounts. + type: boolean + disableReason: + description: The reason why payouts (to all of the account holder's accounts) have been disabled (by the platform). If the `disabled` field is true, this field can be used to explain why. + type: string + disabled: + description: Indicates whether payouts have been disabled (by the platform) for all of the account holder's accounts. A platform may enable and disable this field at their discretion. If this field is true, `allowPayout` will be false and no payouts will be permitted for any of the account holder's accounts. If this field is false, `allowPayout` may or may not be enabled, depending on other factors. + type: boolean + payoutLimit: + $ref: "#/components/schemas/Amount" + description: The maximum amount that payouts are limited to. Only applies if payouts are allowed but limited. + tierNumber: + description: The payout tier that the account holder occupies. + format: int32 + type: integer + x-addedInVersion: "3" + type: object + AccountProcessingState: + properties: + disableReason: + description: The reason why processing has been disabled. + type: string + disabled: + description: Indicates whether the processing of payments is allowed. + type: boolean + processedFrom: + $ref: "#/components/schemas/Amount" + description: The lower bound of the processing tier (i.e., an account holder must have processed at least this amount of money in order to be placed into this tier). + processedTo: + $ref: "#/components/schemas/Amount" + description: The upper bound of the processing tier (i.e., an account holder must have processed less than this amount of money in order to be placed into this tier). + tierNumber: + description: The processing tier that the account holder occupies. + format: int32 + type: integer + x-addedInVersion: "3" + type: object + AccountWrapper: + properties: + Account: + $ref: "#/components/schemas/Account" + Amount: + properties: + currency: + description: The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + maxLength: 3 + minLength: 3 + type: string + value: + description: The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + format: int64 + type: integer + required: + - value + - currency + type: object + BankAccountDetail: + properties: + accountNumber: + description: |- + The bank account number (without separators). + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + accountType: + description: |- + The type of bank account. + Only applicable to bank accounts held in the USA. + The permitted values are: `checking`, `savings`. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + bankAccountName: + description: The name of the bank account. + type: string + bankAccountUUID: + description: | + The unique identifier (UUID) of the Bank Account. + >If, during an account holder create or update request, this field is left blank (but other fields provided), a new Bank Account will be created with a procedurally-generated UUID. + + >If, during an account holder create request, a UUID is provided, the creation of the Bank Account will fail while the creation of the account holder will continue. + + >If, during an account holder update request, a UUID that is not correlated with an existing Bank Account is provided, the update of the account holder will fail. + + >If, during an account holder update request, a UUID that is correlated with an existing Bank Account is provided, the existing Bank Account will be updated. + type: string + bankBicSwift: + description: |- + The bank identifier code. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + bankCity: + description: |- + The city in which the bank branch is located. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + bankCode: + description: |- + The bank code of the banking institution with which the bank account is registered. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + bankName: + description: |- + The name of the banking institution with which the bank account is held. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + branchCode: + description: |- + The branch code of the branch under which the bank account is registered. The value to be specified in this parameter depends on the country of the bank account: + * United States - Routing number + * United Kingdom - Sort code + * Germany - Bankleitzahl + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + checkCode: + description: |- + The check code of the bank account. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + countryCode: + description: |- + The two-letter country code in which the bank account is registered. + >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL'). + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + currencyCode: + description: | + The currency in which the bank account deals. + >The permitted currency codes are defined in ISO-4217 (e.g. 'EUR'). + type: string + iban: + description: |- + The international bank account number. + >The IBAN standard is defined in ISO-13616. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerCity: + description: |- + The city of residence of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerCountryCode: + description: |- + The country code of the country of residence of the bank account owner. + >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL'). + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerDateOfBirth: + deprecated: true + description: |- + The date of birth of the bank account owner. + The date should be in ISO-8601 format yyyy-mm-dd (e.g. 2000-01-31). + type: string + ownerHouseNumberOrName: + description: |- + The house name or number of the residence of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerName: + description: |- + The name of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerNationality: + description: |- + The country code of the country of nationality of the bank account owner. + >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL'). + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerPostalCode: + description: |- + The postal code of the residence of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerState: + description: |- + The state of residence of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + ownerStreet: + description: |- + The street name of the residence of the bank account owner. + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + primaryAccount: + description: If set to true, the bank account is a primary account. + type: boolean + taxId: + description: |- + The tax ID number. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + urlForVerification: + description: |- + The URL to be used for bank account verification. + This may be generated on bank account creation. + + >Refer to [Required information](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process/required-information) for details on field requirements. + type: string + type: object + BankAccountDetailWrapper: + properties: + BankAccountDetail: + $ref: "#/components/schemas/BankAccountDetail" + BusinessDetails: + properties: + doingBusinessAs: + description: The registered name of the company (if it differs from the legal name of the company). + type: string + legalBusinessName: + description: The legal name of the company. + type: string + listedUltimateParentCompany: + description: Information about the parent public company. Required if the account holder is 100% owned by a publicly listed company. + items: + $ref: "#/components/schemas/UltimateParentCompanyWrapper" + type: array + shareholders: + description: Array containing information about individuals associated with the account holder either through ownership or control. For details about how you can identify them, refer to [our verification guide](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-process#identify-ubos). + items: + $ref: "#/components/schemas/ShareholderContactWrapper" + type: array + signatories: + description: |- + Signatories associated with the company. + Each array entry should represent one signatory. + items: + $ref: "#/components/schemas/SignatoryContactWrapper" + type: array + taxId: + description: The tax ID of the company. + type: string + type: object + CloseAccountHolderRequest: + properties: + accountHolderCode: + description: The code of the Account Holder to be closed. + type: string + required: + - accountHolderCode + type: object + CloseAccountHolderResponse: + properties: + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The new status of the Account Holder. + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + CloseAccountRequest: + properties: + accountCode: + description: The code of account to be closed. + type: string + required: + - accountCode + type: object + CloseAccountResponse: + properties: + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + status: + description: |- + The new status of the account. + >Permitted values: `Active`, `Inactive`, `Suspended`, `Closed`. + enum: + - Active + - Closed + - Inactive + - Suspended + type: string + x-addedInVersion: "2" + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + CreateAccountHolderRequest: + properties: + accountHolderCode: + description: |- + Your unique identifier for the prospective account holder. + The length must be between three (3) and fifty (50) characters long. Only letters, digits, and hyphens (-) are allowed. + type: string + accountHolderDetails: + $ref: "#/components/schemas/AccountHolderDetails" + description: The details of the prospective account holder. + createDefaultAccount: + description: |- + If set to **true**, an account with the default options is automatically created for the account holder. + By default, this field is set to **true**. + type: boolean + legalEntity: + description: |- + The legal entity type of the account holder. This determines the information that should be provided in the request. + + Possible values: **Business**, **Individual**, or **NonProfit**. + + * If set to **Business** or **NonProfit**, then `accountHolderDetails.businessDetails` must be provided, with at least one entry in the `accountHolderDetails.businessDetails.shareholders` list. + + * If set to **Individual**, then `accountHolderDetails.individualDetails` must be provided. + enum: + - Business + - Individual + - NonProfit + type: string + processingTier: + description: The starting [processing tier](https://docs.adyen.com/marketplaces-and-platforms/classic/onboarding-and-verification/precheck-kyc-information) for the prospective account holder. + format: int32 + type: integer + x-addedInVersion: "3" + required: + - accountHolderCode + - legalEntity + - accountHolderDetails + type: object + CreateAccountHolderResponse: + properties: + accountCode: + description: The code of a new account created for the account holder. + type: string + accountHolderCode: + description: The code of the new account holder. + type: string + accountHolderDetails: + $ref: "#/components/schemas/AccountHolderDetails" + description: Details of the new account holder. + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The status of the new account holder. + x-addedInVersion: "2" + invalidFields: + description: A list of fields that caused the `/createAccountHolder` request to fail. + items: + $ref: "#/components/schemas/ErrorFieldTypeWrapper" + type: array + x-addedInVersion: "5" + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + verification: + $ref: "#/components/schemas/KYCVerificationResult" + description: The details of KYC Verification of the account holder. + x-addedInVersion: "2" + type: object + CreateAccountRequest: + properties: + accountHolderCode: + description: The code of Account Holder under which to create the account. + type: string + payoutSchedule: + description: |- + The payout schedule of the prospective account. + >Permitted values: `DEFAULT`, `HOLD`, `DAILY`, `WEEKLY`, `MONTHLY`. + enum: + - BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT + - DAILY + - DAILY_AU + - DAILY_EU + - DAILY_SG + - DAILY_US + - HOLD + - MONTHLY + - WEEKLY + - WEEKLY_MON_TO_FRI_AU + - WEEKLY_MON_TO_FRI_EU + - WEEKLY_MON_TO_FRI_US + - WEEKLY_ON_TUE_FRI_MIDNIGHT + - WEEKLY_SUN_TO_THU_AU + - WEEKLY_SUN_TO_THU_US + type: string + payoutScheduleReason: + description: |- + The reason for the payout schedule choice. + >Required if the payoutSchedule is `HOLD`. + type: string + required: + - accountHolderCode + type: object + CreateAccountResponse: + properties: + accountCode: + description: The code of the new account. + type: string + accountHolderCode: + description: The code of the account holder. + type: string + payoutSchedule: + $ref: "#/components/schemas/PayoutScheduleResponse" + description: The payout schedule of the account. + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + status: + description: |- + The status of the account. + >Permitted values: `Active`. + enum: + - Active + - Closed + - Inactive + - Suspended + type: string + x-addedInVersion: "2" + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + DeleteBankAccountRequest: + properties: + accountHolderCode: + description: The code of the Account Holder from which to delete the Bank Account(s). + type: string + bankAccountUUIDs: + description: The code(s) of the Bank Accounts to be deleted. + items: + type: string + type: array + required: + - accountHolderCode + - bankAccountUUIDs + type: object + DeleteLegalArrangementRequest: + properties: + accountHolderCode: + description: The code of the account holder. + type: string + legalArrangements: + description: List of legal arrangements. + items: + $ref: "#/components/schemas/LegalArrangementRequestWrapper" + type: array + required: + - accountHolderCode + - legalArrangements + type: object + DeleteShareholderRequest: + properties: + accountHolderCode: + description: The code of the Account Holder from which to delete the Shareholders. + type: string + shareholderCodes: + description: The code(s) of the Shareholders to be deleted. + items: + type: string + type: array + required: + - accountHolderCode + - shareholderCodes + type: object + DeleteSignatoriesRequest: + properties: + accountHolderCode: + description: The code of the account holder from which to delete the signatories. + type: string + signatoryCodes: + description: Array of codes of the signatories to be deleted. + items: + type: string + type: array + required: + - accountHolderCode + - signatoryCodes + type: object + DocumentDetail: + properties: + accountHolderCode: + description: The code of account holder, to which the document applies. + type: string + x-addedInVersion: "2" + bankAccountUUID: + description: | + The Adyen-generated [`bankAccountUUID`](https://docs.adyen.com/api-explorer/#/Account/latest/post/createAccountHolder__resParam_accountHolderDetails-bankAccountDetails-bankAccountUUID) to which the document must be linked. Refer to [Bank account check](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-checks/bank-account-check#uploading-a-bank-statement) for details on when a document should be submitted. + >Required if the `documentType` is **BANK_STATEMENT**, where a document is being submitted in order to verify a bank account. + type: string + x-addedInVersion: "2" + description: + description: Description of the document. + type: string + documentType: + description: | + The type of the document. Refer to [Verification checks](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-checks) for details on when each document type should be submitted and for the accepted file formats. + + Permitted values: + * **BANK_STATEMENT**: A file containing a bank statement or other document proving ownership of a specific bank account. + * **COMPANY_REGISTRATION_SCREENING** (Supported from v5 and later): A file containing a company registration document. + * **CONSTITUTIONAL_DOCUMENT**: A file containing information about the account holder's legal arrangement. + * **PASSPORT**: A file containing the identity page(s) of a passport. + * **ID_CARD_FRONT**: A file containing only the front of the ID card. In order for a document to be usable, both the **ID_CARD_FRONT** and **ID_CARD_BACK** must be submitted. + * **ID_CARD_BACK**: A file containing only the back of the ID card. In order for a document to be usable, both the **ID_CARD_FRONT** and **ID_CARD_BACK** must be submitted. + * **DRIVING_LICENCE_FRONT**: A file containing only the front of the driving licence. In order for a document to be usable, both the **DRIVING_LICENCE_FRONT** and **DRIVING_LICENCE_BACK** must be submitted. + * **DRIVING_LICENCE_BACK**: A file containing only the back of the driving licence. In order for a document to be usable, both the **DRIVING_LICENCE_FRONT** and **DRIVING_LICENCE_FRONT** must be submitted. + enum: + - BANK_STATEMENT + - BSN + - DRIVING_LICENCE + - DRIVING_LICENCE_BACK + - DRIVING_LICENCE_FRONT + - ID_CARD + - ID_CARD_BACK + - ID_CARD_FRONT + - PASSPORT + - PROOF_OF_RESIDENCY + - SSN + type: string + filename: + description: Filename of the document. + type: string + shareholderCode: + description: |- + The Adyen-generated [`shareholderCode`](https://docs.adyen.com/api-explorer/#/Account/latest/post/createAccountHolder__resParam_accountHolderDetails-businessDetails-shareholders-shareholderCode) to which the document must be linked. Refer to [Verification checks](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-checks) for details on when a document should be submitted. + >Required if the account holder has a `legalEntity` of type **Business** and the `documentType` is either **PASSPORT**, **ID_CARD_FRONT**, **ID_CARD_BACK**, **DRIVING_LICENCE_FRONT**, or **DRIVING_LICENCE_BACK**. + type: string + x-addedInVersion: "2" + signatoryCode: + description: The Adyen-generated [`signatoryCode`](https://docs.adyen.com/api-explorer/#/Account/v6/post/createAccountHolder__resParam_accountHolderDetails-businessDetails-signatories-signatoryCode) to which the document must be linked. + type: string + required: + - documentType + type: object + DocumentDetailWrapper: + properties: + DocumentDetail: + $ref: "#/components/schemas/DocumentDetail" + ErrorFieldType: + properties: + errorCode: + description: The validation error code. + format: int32 + type: integer + errorDescription: + description: A description of the validation error. + type: string + fieldType: + $ref: "#/components/schemas/FieldType" + description: The type of error field. + type: object + ErrorFieldTypeWrapper: + properties: + ErrorFieldType: + $ref: "#/components/schemas/ErrorFieldType" + FieldType: + properties: + field: + description: The full name of the property. + type: string + fieldName: + description: The type of the field. + enum: + - accountCode + - accountHolderCode + - accountHolderDetails + - accountNumber + - accountStateType + - accountStatus + - accountType + - address + - balanceAccount + - balanceAccountActive + - balanceAccountCode + - balanceAccountId + - bankAccount + - bankAccountCode + - bankAccountName + - bankAccountUUID + - bankBicSwift + - bankCity + - bankCode + - bankName + - bankStatement + - branchCode + - businessContact + - cardToken + - checkCode + - city + - companyRegistration + - constitutionalDocument + - controller + - country + - countryCode + - currency + - currencyCode + - dateOfBirth + - destinationAccountCode + - document + - documentContent + - documentExpirationDate + - documentIssuerCountry + - documentIssuerState + - documentName + - documentNumber + - documentType + - doingBusinessAs + - drivingLicence + - drivingLicenceBack + - drivingLicenceFront + - drivingLicense + - email + - firstName + - formType + - fullPhoneNumber + - gender + - hopWebserviceUser + - houseNumberOrName + - iban + - idCard + - idNumber + - identityDocument + - individualDetails + - infix + - jobTitle + - lastName + - lastReviewDate + - legalArrangement + - legalArrangementCode + - legalArrangementEntity + - legalArrangementEntityCode + - legalArrangementLegalForm + - legalArrangementMember + - legalArrangementMembers + - legalArrangementName + - legalArrangementReference + - legalArrangementRegistrationNumber + - legalArrangementTaxNumber + - legalArrangementType + - legalBusinessName + - legalEntity + - legalEntityType + - logo + - merchantAccount + - merchantCategoryCode + - merchantHouseNumber + - merchantReference + - microDeposit + - name + - nationality + - originalReference + - ownerCity + - ownerCountryCode + - ownerDateOfBirth + - ownerHouseNumberOrName + - ownerName + - ownerPostalCode + - ownerState + - ownerStreet + - passport + - passportNumber + - payoutMethod + - payoutMethodCode + - payoutSchedule + - pciSelfAssessment + - personalData + - phoneCountryCode + - phoneNumber + - postalCode + - primaryCurrency + - reason + - returnUrl + - schedule + - shareholder + - shareholderCode + - shareholderCodeAndSignatoryCode + - shareholderCodeOrSignatoryCode + - shareholderType + - shareholderTypes + - shopperInteraction + - signatory + - signatoryCode + - socialSecurityNumber + - sourceAccountCode + - splitAccount + - splitConfigurationUUID + - splitCurrency + - splitValue + - splits + - stateOrProvince + - status + - stockExchange + - stockNumber + - stockTicker + - store + - storeDetail + - storeName + - storeReference + - street + - taxId + - tier + - tierNumber + - transferCode + - ultimateParentCompany + - ultimateParentCompanyAddressDetails + - ultimateParentCompanyAddressDetailsCountry + - ultimateParentCompanyBusinessDetails + - ultimateParentCompanyBusinessDetailsLegalBusinessName + - ultimateParentCompanyBusinessDetailsRegistrationNumber + - ultimateParentCompanyCode + - ultimateParentCompanyStockExchange + - ultimateParentCompanyStockNumber + - ultimateParentCompanyStockNumberOrStockTicker + - ultimateParentCompanyStockTicker + - unknown + - value + - verificationType + - virtualAccount + - visaNumber + - webAddress + - year + type: string + shareholderCode: + description: The code of the shareholder that the field belongs to. If empty, the field belongs to an account holder. + type: string + type: object + FieldTypeWrapper: + properties: + FieldType: + $ref: "#/components/schemas/FieldType" + GenericResponse: + properties: + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + GetAccountHolderRequest: + properties: + accountCode: + description: |- + The code of the account of which to retrieve the details. + > Required if no `accountHolderCode` is provided. + type: string + accountHolderCode: + description: |- + The code of the account holder of which to retrieve the details. + > Required if no `accountCode` is provided. + type: string + type: object + GetAccountHolderResponse: + properties: + accountHolderCode: + description: The code of the account holder. + type: string + accountHolderDetails: + $ref: "#/components/schemas/AccountHolderDetails" + description: Details of the account holder. + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The status of the account holder. + x-addedInVersion: "2" + accounts: + description: A list of the accounts under the account holder. + items: + $ref: "#/components/schemas/AccountWrapper" + type: array + legalEntity: + description: The legal entity of the account holder. + enum: + - Business + - Individual + - NonProfit + type: string + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + verification: + $ref: "#/components/schemas/KYCVerificationResult" + description: The details of KYC Verification of the account holder. + x-addedInVersion: "2" + type: object + GetAccountHolderStatusResponse: + properties: + accountHolderCode: + description: The code of the Account Holder. + type: string + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The status of the Account Holder. + x-addedInVersion: "2" + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + GetTaxFormRequest: + properties: + accountHolderCode: + description: The account holder code you provided when you created the account holder. + type: string + formType: + description: Type of the requested tax form. For example, 1099-K. + type: string + year: + description: Applicable tax year in the YYYY format. + format: int32 + type: integer + required: + - accountHolderCode + - formType + - year + type: object + GetTaxFormResponse: + properties: + content: + contentEncoding: base64 + description: The content of the tax form in the Base64 binary format. + type: string + contentType: + description: The content type of the tax form. + type: string + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + GetUploadedDocumentsRequest: + properties: + accountHolderCode: + description: The code of the Account Holder for which to retrieve the documents. + type: string + bankAccountUUID: + description: The code of the Bank Account for which to retrieve the documents. + type: string + x-addedInVersion: "2" + shareholderCode: + description: The code of the Shareholder for which to retrieve the documents. + type: string + required: + - accountHolderCode + type: object + GetUploadedDocumentsResponse: + properties: + documentDetails: + description: A list of the documents and their details. + items: + $ref: "#/components/schemas/DocumentDetailWrapper" + type: array + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + IndividualDetails: + properties: + name: + $ref: "#/components/schemas/ViasName" + description: |- + The name of the individual. + >Make sure your account holder registers using the name shown on their Photo ID. + personalData: + $ref: "#/components/schemas/ViasPersonalData" + description: Personal information of the individual. + type: object + KYCBankAccountCheckResult: + properties: + bankAccountUUID: + description: The unique ID of the bank account to which the check applies. + type: string + checks: + description: A list of the checks and their statuses. + items: + $ref: "#/components/schemas/KYCCheckStatusData" + type: array + type: object + KYCCheckResult: + properties: + checks: + description: A list of the checks and their statuses. + items: + $ref: "#/components/schemas/KYCCheckStatusData" + type: array + type: object + KYCCheckStatusData: + properties: + requiredFields: + description: A list of the fields required for execution of the check. + items: + type: string + type: array + status: + description: |- + The status of the check. + + Possible values: **AWAITING_DATA** , **DATA_PROVIDED**, **FAILED**, **INVALID_DATA**, **PASSED**, **PENDING**, **RETRY_LIMIT_REACHED**. + enum: + - AWAITING_DATA + - DATA_PROVIDED + - FAILED + - INVALID_DATA + - PASSED + - PENDING + - PENDING_REVIEW + - RETRY_LIMIT_REACHED + - UNCHECKED + type: string + summary: + $ref: "#/components/schemas/KYCCheckSummary" + description: A summary of the execution of the check. + type: + description: |- + The type of check. + + Possible values: + + * **BANK_ACCOUNT_VERIFICATION**: Used in v5 and earlier. Replaced by **PAYOUT_METHOD_VERIFICATION** in v6 and later. + + * **COMPANY_VERIFICATION** + + * **CARD_VERIFICATION** + + * **IDENTITY_VERIFICATION** + + * **LEGAL_ARRANGEMENT_VERIFICATION** + + * **NONPROFIT_VERIFICATION** + + * **PASSPORT_VERIFICATION** + + * **PAYOUT_METHOD_VERIFICATION**: Used in v6 and later. + + * **PCI_VERIFICATION** + enum: + - BANK_ACCOUNT_VERIFICATION + - CARD_VERIFICATION + - COMPANY_VERIFICATION + - IDENTITY_VERIFICATION + - LEGAL_ARRANGEMENT_VERIFICATION + - NONPROFIT_VERIFICATION + - PASSPORT_VERIFICATION + - PAYOUT_METHOD_VERIFICATION + - PCI_VERIFICATION + type: string + required: + - type + - status + type: object + KYCCheckSummary: + properties: + code: + description: The code of the check. + format: int32 + type: integer + description: + description: A description of the check. + type: string + required: + - code + type: object + KYCShareholderCheckResult: + properties: + checks: + description: A list of the checks and their statuses. + items: + $ref: "#/components/schemas/KYCCheckStatusData" + type: array + shareholderCode: + description: The code of the shareholder to which the check applies. + type: string + type: object + KYCSignatoryCheckResult: + properties: + checks: + description: A list of the checks and their statuses. + items: + $ref: "#/components/schemas/KYCCheckStatusData" + type: array + signatoryCode: + description: The code of the signatory to which the check applies. + type: string + type: object + KYCVerificationResult: + properties: + accountHolder: + $ref: "#/components/schemas/KYCCheckResult" + description: The results of the checks on the account holder. + bankAccounts: + description: The results of the checks on the bank accounts. + items: + $ref: "#/components/schemas/KYCBankAccountCheckResult" + type: array + shareholders: + description: The results of the checks on the shareholders. + items: + $ref: "#/components/schemas/KYCShareholderCheckResult" + type: array + signatories: + description: The results of the checks on the signatories. + items: + $ref: "#/components/schemas/KYCSignatoryCheckResult" + type: array + type: object + LegalArrangementRequest: + properties: + legalArrangementCode: + description: The code of the legal arrangement to be deleted. If you also send `legalArrangementEntityCodes`, only the entities listed will be deleted. + type: string + legalArrangementEntityCodes: + description: List of legal arrangement entities to be deleted. + items: + type: string + type: array + required: + - legalArrangementCode + type: object + LegalArrangementRequestWrapper: + properties: + LegalArrangementRequest: + $ref: "#/components/schemas/LegalArrangementRequest" + PayoutScheduleResponse: + properties: + nextScheduledPayout: + description: The date of the next scheduled payout. + format: date-time + type: string + schedule: + description: |- + The payout schedule of the account. + Permitted values: `DEFAULT`, `DAILY`, `DAILY_US`, `DAILY_EU`, `DAILY_AU`, `DAILY_SG`, `WEEKLY`, `WEEKLY_ON_TUE_FRI_MIDNIGHT`, `BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT`, `MONTHLY`, `HOLD`. + enum: + - BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT + - DAILY + - DAILY_AU + - DAILY_EU + - DAILY_SG + - DAILY_US + - HOLD + - MONTHLY + - WEEKLY + - WEEKLY_MON_TO_FRI_AU + - WEEKLY_MON_TO_FRI_EU + - WEEKLY_MON_TO_FRI_US + - WEEKLY_ON_TUE_FRI_MIDNIGHT + - WEEKLY_SUN_TO_THU_AU + - WEEKLY_SUN_TO_THU_US + type: string + type: object + PersonalDocumentData: + properties: + expirationDate: + description: |- + The expiry date of the document, + in ISO-8601 YYYY-MM-DD format. For example, **2000-01-31**. + type: string + issuerCountry: + description: |- + The country where the document was issued, in the two-character + [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **NL**. + maxLength: 2 + minLength: 2 + type: string + issuerState: + description: The state where the document was issued (if applicable). + type: string + number: + description: The number in the document. + type: string + type: + description: |- + The type of the document. Possible values: **ID**, **DRIVINGLICENSE**, **PASSPORT**, **SOCIALSECURITY**, **VISA**. + + To delete an existing entry for a document `type`, send only the `type` field in your request. + enum: + - DRIVINGLICENSE + - ID + - PASSPORT + - SOCIALSECURITY + - VISA + type: string + required: + - type + type: object + PersonalDocumentDataWrapper: + properties: + PersonalDocumentData: + $ref: "#/components/schemas/PersonalDocumentData" + ServiceError: + properties: + errorCode: + description: The error code mapped to the error message. + type: string + errorType: + description: The category of the error. + type: string + message: + description: A short explanation of the issue. + type: string + pspReference: + description: The PSP reference of the payment. + type: string + status: + description: The HTTP response status. + format: int32 + type: integer + type: object + ShareholderContact: + properties: + address: + $ref: "#/components/schemas/ViasAddress" + description: The address of the person. + email: + description: The e-mail address of the person. + type: string + fullPhoneNumber: + description: |- + The phone number of the person provided as a single string. It will be handled as a landline phone. + Examples: "0031 6 11 22 33 44", "+316/1122-3344", "(0031) 611223344" + type: string + jobTitle: + description: |- + Job title of the person. Required when the `shareholderType` is **Controller**. + + Example values: **Chief Executive Officer**, **Chief Financial Officer**, **Chief Operating Officer**, **President**, **Vice President**, **Executive President**, **Managing Member**, **Partner**, **Treasurer**, **Director**, or **Other**. + type: string + name: + $ref: "#/components/schemas/ViasName" + description: The name of the person. + personalData: + $ref: "#/components/schemas/ViasPersonalData" + description: Contains information about the person. + phoneNumber: + $ref: "#/components/schemas/ViasPhoneNumber" + description: The phone number of the person. + shareholderCode: + description: | + The unique identifier (UUID) of the shareholder entry. + >**If, during an Account Holder create or update request, this field is left blank (but other fields provided), a new Shareholder will be created with a procedurally-generated UUID.** + + >**If, during an Account Holder create request, a UUID is provided, the creation of Account Holder will fail with a validation Error..** + + >**If, during an Account Holder update request, a UUID that is not correlated with an existing Shareholder is provided, the update of the Shareholder will fail.** + + >**If, during an Account Holder update request, a UUID that is correlated with an existing Shareholder is provided, the existing Shareholder will be updated.** + type: string + shareholderType: + description: |- + Specifies how the person is associated with the account holder. + + Possible values: + + * **Owner**: Individuals who directly or indirectly own 25% or more of a company. + + * **Controller**: Individuals who are members of senior management staff responsible for managing a company or organization. + enum: + - Controller + - Owner + - Signatory + type: string + webAddress: + description: The URL of the person's website. + type: string + type: object + ShareholderContactWrapper: + properties: + ShareholderContact: + $ref: "#/components/schemas/ShareholderContact" + SignatoryContact: + properties: + address: + $ref: "#/components/schemas/ViasAddress" + description: The address of the person. + email: + description: The e-mail address of the person. + type: string + fullPhoneNumber: + description: |- + The phone number of the person provided as a single string. It will be handled as a landline phone. + Examples: "0031 6 11 22 33 44", "+316/1122-3344", "(0031) 611223344" + type: string + jobTitle: + description: |- + Job title of the signatory. + + Example values: **Chief Executive Officer**, **Chief Financial Officer**, **Chief Operating Officer**, **President**, **Vice President**, **Executive President**, **Managing Member**, **Partner**, **Treasurer**, **Director**, or **Other**. + type: string + name: + $ref: "#/components/schemas/ViasName" + description: The name of the person. + personalData: + $ref: "#/components/schemas/ViasPersonalData" + description: Contains information about the person. + phoneNumber: + $ref: "#/components/schemas/ViasPhoneNumber" + description: The phone number of the person. + signatoryCode: + description: | + The unique identifier (UUID) of the signatory. + >**If, during an Account Holder create or update request, this field is left blank (but other fields provided), a new Signatory will be created with a procedurally-generated UUID.** + + >**If, during an Account Holder create request, a UUID is provided, the creation of the Signatory will fail while the creation of the Account Holder will continue.** + + >**If, during an Account Holder update request, a UUID that is not correlated with an existing Signatory is provided, the update of the Signatory will fail.** + + >**If, during an Account Holder update request, a UUID that is correlated with an existing Signatory is provided, the existing Signatory will be updated.** + type: string + signatoryReference: + description: Your reference for the signatory. + type: string + webAddress: + description: The URL of the person's website. + type: string + type: object + SignatoryContactWrapper: + properties: + SignatoryContact: + $ref: "#/components/schemas/SignatoryContact" + SuspendAccountHolderRequest: + properties: + accountHolderCode: + description: The code of the account holder to be suspended. + type: string + required: + - accountHolderCode + type: object + SuspendAccountHolderResponse: + properties: + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The new status of the Account Holder. + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + UltimateParentCompany: + properties: + address: + $ref: "#/components/schemas/ViasAddress" + description: Address of the ultimate parent company. + businessDetails: + $ref: "#/components/schemas/UltimateParentCompanyBusinessDetails" + description: Details about the ultimate parent company's business. + ultimateParentCompanyCode: + description: Adyen-generated unique alphanumeric identifier (UUID) for the entry, returned in the response when you create an ultimate parent company. Required when updating an existing entry in an `/updateAccountHolder` request. + type: string + type: object + UltimateParentCompanyBusinessDetails: + properties: + legalBusinessName: + description: The legal name of the company. + type: string + registrationNumber: + description: The registration number of the company. + type: string + stockExchange: + description: Market Identifier Code (MIC). + type: string + stockNumber: + description: International Securities Identification Number (ISIN). + type: string + stockTicker: + description: Stock Ticker symbol. + type: string + type: object + UltimateParentCompanyWrapper: + properties: + UltimateParentCompany: + $ref: "#/components/schemas/UltimateParentCompany" + UnSuspendAccountHolderRequest: + properties: + accountHolderCode: + description: The code of the account holder to be reinstated. + type: string + required: + - accountHolderCode + type: object + UnSuspendAccountHolderResponse: + properties: + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The new status of the Account Holder. + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + type: object + UpdateAccountHolderRequest: + properties: + accountHolderCode: + description: The code of the Account Holder to be updated. + type: string + accountHolderDetails: + $ref: "#/components/schemas/AccountHolderDetails" + description: |- + The details to which the Account Holder should be updated. + + Required if a processingTier is not provided. + processingTier: + description: |- + The processing tier to which the Account Holder should be updated. + >The processing tier can not be lowered through this request. + + >Required if accountHolderDetails are not provided. + format: int32 + type: integer + x-addedInVersion: "3" + required: + - accountHolderCode + type: object + UpdateAccountHolderResponse: + properties: + accountHolderCode: + description: The code of the account holder. + type: string + accountHolderDetails: + $ref: "#/components/schemas/AccountHolderDetails" + description: Details of the account holder. + accountHolderStatus: + $ref: "#/components/schemas/AccountHolderStatus" + description: The new status of the account holder. + x-addedInVersion: "2" + invalidFields: + description: in case the account holder has not been updated, contains account holder fields, that did not pass the validation. + items: + $ref: "#/components/schemas/ErrorFieldTypeWrapper" + type: array + x-addedInVersion: "5" + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + updatedFields: + description: A list of the fields updated through the request. + items: + $ref: "#/components/schemas/FieldTypeWrapper" + type: array + verification: + $ref: "#/components/schemas/KYCVerificationResult" + description: The details of KYC Verification of the account holder. + x-addedInVersion: "2" + type: object + UpdateAccountHolderStateRequest: + properties: + accountHolderCode: + description: The code of the Account Holder on which to update the state. + type: string + disable: + description: If true, disable the requested state. If false, enable the requested state. + type: boolean + reason: + description: |- + The reason that the state is being updated. + >Required if the state is being disabled. + type: string + stateType: + description: |- + The state to be updated. + >Permitted values are: `Processing`, `Payout` + enum: + - LimitedPayout + - LimitedProcessing + - LimitlessPayout + - LimitlessProcessing + - Payout + - Processing + type: string + required: + - accountHolderCode + - stateType + - disable + type: object + UpdateAccountRequest: + properties: + accountCode: + description: The code of the account to update. + type: string + payoutSchedule: + $ref: "#/components/schemas/UpdatePayoutScheduleRequest" + description: The details of the payout schedule, to which the account should be updated. + required: + - accountCode + - payoutSchedule + type: object + UpdateAccountResponse: + properties: + accountCode: + description: The code of the account. + type: string + payoutSchedule: + $ref: "#/components/schemas/PayoutScheduleResponse" + description: The payout schedule of the account. + pspReference: + description: The reference of a request. Can be used to uniquely identify the request. + type: string + resultCode: + description: The result code. + type: string + submittedAsync: + description: |- + Indicates whether the request is processed asynchronously. Depending on the request's platform settings, the following scenarios may be applied: + * **true**: The request is queued and will be executed when the providing service is available in the order in which the requests are received. + * **false**: The processing of the request is immediately attempted; it may result in an error if the providing service is unavailable. + type: boolean + required: + - accountCode + type: object + UpdatePayoutScheduleRequest: + properties: + action: + description: |- + Direction on how to handle any payouts that have already been scheduled. + Permitted values: + * `CLOSE` will close the existing batch of payouts. + * `UPDATE` will reschedule the existing batch to the new schedule. + * `NOTHING` (**default**) will allow the payout to proceed. + enum: + - CLOSE + - NOTHING + - UPDATE + type: string + reason: + description: |- + The reason for the payout schedule update. + > This field is required when the `schedule` parameter is set to `HOLD`. + type: string + schedule: + description: |- + The payout schedule to which the account is to be updated. + Permitted values: `DAILY`, `DAILY_US`, `DAILY_EU`, `DAILY_AU`, `DAILY_SG`, `WEEKLY`, `WEEKLY_ON_TUE_FRI_MIDNIGHT`, `BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT`, `MONTHLY`, `HOLD`. + `HOLD` will prevent scheduled payouts from happening but will still allow manual payouts to occur. + enum: + - BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT + - DAILY + - DAILY_AU + - DAILY_EU + - DAILY_SG + - DAILY_US + - HOLD + - MONTHLY + - WEEKLY + - WEEKLY_MON_TO_FRI_AU + - WEEKLY_MON_TO_FRI_EU + - WEEKLY_MON_TO_FRI_US + - WEEKLY_ON_TUE_FRI_MIDNIGHT + - WEEKLY_SUN_TO_THU_AU + - WEEKLY_SUN_TO_THU_US + type: string + required: + - schedule + type: object + UploadDocumentRequest: + properties: + accountHolderCode: + deprecated: true + description: The code of the account holder, for which the document is submitted. + type: string + bankAccountUUID: + deprecated: true + description: |- + The unique ID of the bank account, for which the document is submitted. + >Required if the document is being submitted in order to verify a bank account. + type: string + documentContent: + contentEncoding: base64 + description: |- + The content of the document, in Base64-encoded string format. + + To learn about document requirements, refer to [Verification checks](https://docs.adyen.com/marketplaces-and-platforms/classic/verification-checks). + type: string + documentDetail: + $ref: "#/components/schemas/DocumentDetail" + description: Details of the document being submitted. + shareholderCode: + deprecated: true + description: |- + The code of the shareholder, for which the document is submitted. + >Required if the document is being submitted in order to verify a shareholder. + type: string + required: + - documentDetail + - documentContent + type: object + ViasAddress: + properties: + city: + description: The name of the city. Required if the `houseNumberOrName`, `street`, `postalCode`, or `stateOrProvince` are provided. + type: string + country: + description: The two-character country code of the address in ISO-3166-1 alpha-2 format. For example, **NL**. + type: string + houseNumberOrName: + description: The number or name of the house. + type: string + postalCode: + description: |- + The postal code. Required if the `houseNumberOrName`, `street`, `city`, or `stateOrProvince` are provided. + + Maximum length: + + * 5 digits for addresses in the US. + + * 10 characters for all other countries. + type: string + stateOrProvince: + description: | + The abbreviation of the state or province. Required if the `houseNumberOrName`, `street`, `city`, or `postalCode` are provided. + + Maximum length: + + * 2 characters for addresses in the US or Canada. + + * 3 characters for all other countries. + type: string + street: + description: The name of the street. Required if the `houseNumberOrName`, `city`, `postalCode`, or `stateOrProvince` are provided. + type: string + required: + - country + type: object + ViasName: + properties: + firstName: + description: The first name. + maxLength: 80 + type: string + gender: + description: |- + The gender. + >The following values are permitted: `MALE`, `FEMALE`, `UNKNOWN`. + enum: + - MALE + - FEMALE + - UNKNOWN + maxLength: 1 + type: string + infix: + description: |- + The name's infix, if applicable. + >A maximum length of twenty (20) characters is imposed. + maxLength: 20 + type: string + lastName: + description: The last name. + maxLength: 80 + type: string + type: object + ViasPersonalData: + properties: + dateOfBirth: + description: The person's date of birth, in ISO-8601 YYYY-MM-DD format. For example, **2000-01-31**. + type: string + documentData: + description: Array that contains information about the person's identification document. You can submit only one entry per document type. + items: + $ref: "#/components/schemas/PersonalDocumentDataWrapper" + type: array + x-addedInVersion: "3" + idNumber: + deprecated: true + description: An ID number of the person. + type: string + x-deprecatedInVersion: "3" + x-deprecatedMessage: Use `individualDetails.personalData.documentData.number` instead. + nationality: + description: | + The nationality of the person represented by a two-character country code, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **NL**. + maxLength: 2 + minLength: 2 + type: string + type: object + ViasPhoneNumber: + properties: + phoneCountryCode: + description: |- + The two-character country code of the phone number. + >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL'). + type: string + phoneNumber: + description: |- + The phone number. + >The inclusion of the phone number country code is not necessary. + type: string + phoneType: + description: |- + The type of the phone number. + >The following values are permitted: `Landline`, `Mobile`, `SIP`, `Fax`. + enum: + - Fax + - Landline + - Mobile + - SIP + type: string + type: object + securitySchemes: + ApiKeyAuth: + in: header + name: X-API-Key + type: apiKey + BasicAuth: + scheme: basic + type: http +x-groups: + - Account holders + - Accounts + - Verification diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_accounting.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_accounting.yaml new file mode 100644 index 000000000..8ed1aee05 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_accounting.yaml @@ -0,0 +1,45257 @@ +openapi: 3.1.0 +servers: + - description: Production + url: https://api.codat.io +info: + contact: + email: support@codat.io + name: Codat + description: |- + A flexible API for pulling accounting data, normalized and aggregated from 20 accounting integrations. + + Standardize how you connect to your customers’ accounting software. View, create, update, and delete data in the same way for all the leading accounting platforms. + + [Read more...](https://docs.codat.io/accounting-api/overview) + + [See our OpenAPI spec](https://github.com/codatio/oas) + termsOfService: https://www.codat.io/legals/ + title: Accounting API + version: 2.1.0 + x-apisguru-categories: + - financial + x-logo: + url: https://static.codat.io/public/branding/codat-icon-blue.svg + x-origin: + - format: openapi + url: https://raw.githubusercontent.com/codatio/oas/main/json/Codat-Accounting.json + version: "3.1" + x-providerName: codat.io + x-serviceName: accounting +security: + - auth_header: [] +tags: + - description: Accounts + name: Accounts + - description: Account transactions + name: Account transactions + - description: Bank accounts + name: Bank accounts + - description: Bank transactions for bank accounts + name: Bank account transactions + - description: Bills + name: Bills + - description: Bill credit notes + name: Bill credit notes + - description: Bill payments + name: Bill payments + - description: Credit notes + name: Credit notes + - description: Customers + name: Customers + - description: Direct costs + name: Direct costs + - description: Direct incomes + name: Direct incomes + - description: Financials + name: Financials + - description: Company info + name: Company info + - description: Invoices + name: Invoices + - description: Items + name: Items + - description: Journals + name: Journals + - description: Journal entries + name: Journal entries + - description: Payments + name: Payments + - description: Payment methods + name: Payment methods + - description: Purchase orders + name: Purchase orders + - description: Sales orders + name: Sales orders + - description: Suppliers + name: Suppliers + - description: Tax rates + name: Tax rates + - description: Tracking categories + name: Tracking categories + - description: Transfers + name: Transfers + - description: Reports + name: Reports +paths: + "/companies/{companyId}/connections/{connectionId}/data/accountTransactions": + get: + description: Gets the account transactions for a given company. + operationId: list-account-transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AccountTransactions" + description: Success + summary: List account transactions + tags: + - Account transactions + "/companies/{companyId}/connections/{connectionId}/data/accountTransactions/{accountTransactionId}": + get: + description: Gets the account transactions for a given company.Gets the specified account transaction for a given company and connection. + operationId: get-account-transaction + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: accountTransactionId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AccountTransaction" + description: Success + summary: Get account transaction + tags: + - Account transactions + "/companies/{companyId}/connections/{connectionId}/data/bankAccounts": + get: + description: Gets the list of bank accounts for a given connection + operationId: list-bank-accounts + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankAccounts" + description: Success + summary: List bank accounts + tags: + - Bank accounts + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/bankAccounts/{accountId}": + get: + deprecated: true + description: Gets the bank account with a given ID + operationId: get-bank-account + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankAccount" + description: Success + summary: Get bank account + tags: + - Bank accounts + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/accountId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/bankAccounts/{accountId}/bankTransactions": + get: + description: Gets bank transactions for a given bank account ID + operationId: list-bank-account-transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - description: Unique identifier for an account + in: path + name: accountId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankTransactionsResponse" + description: Success + summary: List bank transactions for bank account + tags: + - Bank account transactions + "/companies/{companyId}/connections/{connectionId}/data/bills/{billId}/attachments": + get: + description: Get bill attachments + operationId: get-bill-attachments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: List bill attachments + tags: + - Bills + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/bills/{billId}/attachments/{attachmentId}": + get: + description: Get bill attachment + operationId: get-bill-attachment + parameters: + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get bill attachment + tags: + - Bills + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/bills/{billId}/attachments/{attachmentId}/download": + get: + description: Download bill attachment + operationId: download-bill-attachment + parameters: + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download bill attachment + tags: + - Bills + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/customers/{customerId}/attachments": + get: + description: Get customer attachments + operationId: get-customer-attachments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: List customer attachments + tags: + - Customers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: customerId + required: true + schema: + type: string + "/companies/{companyId}/connections/{connectionId}/data/customers/{customerId}/attachments/{attachmentId}": + get: + description: Get customer attachment + operationId: get-customer-attachment + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get customer attachment + tags: + - Customers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: customerId + required: true + schema: + type: string + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/customers/{customerId}/attachments/{attachmentId}/download": + get: + description: Download customer attachment + operationId: download-customer-attachment + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download customer attachment + tags: + - Customers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: customerId + required: true + schema: + type: string + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/directCosts": + get: + description: Gets the direct costs for the company. + operationId: get-direct-costs + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/DirectCosts" + description: Success + summary: List direct costs + tags: + - Direct costs + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/directCosts/{directCostId}": + get: + deprecated: true + description: Gets the specified direct cost for a given company. + operationId: get-direct-cost + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/DirectCost" + description: Success + summary: Get direct cost + tags: + - Direct costs + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directCostId" + "/companies/{companyId}/connections/{connectionId}/data/directCosts/{directCostId}/attachments": + get: + description: Gets all attachments for the specified direct cost for a given company. + operationId: list-direct-cost-attachments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: List direct cost attachments + tags: + - Direct costs + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directCostId" + "/companies/{companyId}/connections/{connectionId}/data/directCosts/{directCostId}/attachments/{attachmentId}": + get: + description: Gets the specified direct cost attachment for a given company. + operationId: get-direct-cost-attachment + parameters: + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get direct cost attachment + tags: + - Direct costs + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directCostId" + "/companies/{companyId}/connections/{connectionId}/data/directCosts/{directCostId}/attachments/{attachmentId}/download": + get: + description: Downloads an attachment for the specified direct cost for a given company. + operationId: download-direct-cost-attachment + parameters: + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download direct cost attachment + tags: + - Direct costs + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directCostId" + "/companies/{companyId}/connections/{connectionId}/data/directIncomes": + get: + description: Gets the direct incomes for a given company. + operationId: get-direct-incomes + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/DirectIncomes" + description: Success + summary: Get direct incomes + tags: + - Direct incomes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/directIncomes/{directIncomeId}": + get: + deprecated: true + description: Gets the specified direct income for a given company and connection. + operationId: get-direct-income + parameters: + - in: path + name: directIncomeId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/DirectIncome" + description: Success + summary: Get direct income + tags: + - Direct incomes + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/directIncomes/{directIncomeId}/attachments": + get: + description: Gets all attachments for the specified direct income for a given company. + operationId: list-direct-income-attachments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: List direct income attachments + tags: + - Direct incomes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directIncomeId" + "/companies/{companyId}/connections/{connectionId}/data/directIncomes/{directIncomeId}/attachments/{attachmentId}": + get: + description: Gets the specified direct income attachment for a given company. + operationId: get-direct-income-attachment + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get direct income attachment + tags: + - Direct incomes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directIncomeId" + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/directIncomes/{directIncomeId}/attachments/{attachmentId}/download": + get: + description: Downloads an attachment for the specified direct income for a given company. + operationId: download-direct-income-attachment + parameters: + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download direct income attachment + tags: + - Direct incomes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directIncomeId" + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/invoices/{invoiceId}/attachments": + get: + description: Get invoice attachments + operationId: get-invoice-attachments + parameters: + - $ref: "#/components/parameters/invoiceId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: Get invoice attachments + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/invoices/{invoiceId}/attachments/{attachmentId}": + get: + description: Get invoice attachment + operationId: get-invoice-attachment + parameters: + - $ref: "#/components/parameters/invoiceId" + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get invoice attachment + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/invoices/{invoiceId}/attachments/{attachmentId}/download": + get: + description: Download invoice attachments + operationId: download-invoice-attachment + parameters: + - $ref: "#/components/parameters/invoiceId" + - $ref: "#/components/parameters/attachmentId" + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download invoice attachment + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/suppliers/{supplierId}/attachments": + get: + description: Get supplier attachments + operationId: list-supplier-attachments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AttachmentsDataset" + description: Success + summary: List supplier attachments + tags: + - Suppliers + parameters: + - $ref: "#/components/parameters/supplierId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/suppliers/{supplierId}/attachments/{attachmentId}": + get: + description: Get supplier attachment + operationId: get-supplier-attachment + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Attachment" + description: Success + summary: Get supplier attachment + tags: + - Suppliers + parameters: + - $ref: "#/components/parameters/supplierId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/suppliers/{supplierId}/attachments/{attachmentId}/download": + get: + description: Download supplier attachment + operationId: download-supplier-attachment + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Download supplier attachment + tags: + - Suppliers + parameters: + - $ref: "#/components/parameters/supplierId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/attachmentId" + "/companies/{companyId}/connections/{connectionId}/data/transfers": + get: + description: Gets the transfers for a given company. + operationId: list-transfers + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Transfers" + description: Success + summary: List transfers + tags: + - Transfers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/data/transfers/{transferId}": + get: + deprecated: true + description: Gets the specified transfer for a given company. + operationId: get-transfer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Transfer" + description: Success + summary: Get transfer + tags: + - Transfers + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: transferId + required: true + schema: + type: string + "/companies/{companyId}/connections/{connectionId}/options/bankAccounts": + get: + description: |- + Get create/update bank account model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bankAccounts) for integrations that support creating and updating bank accounts. + operationId: get-create-update-bankAccounts-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + validation: + information: + - details: Needs to be of the format '{No.}-{Name}' + field: AccountName + warnings: [] + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: false + type: String + currency: + description: The currency of the bank account + displayName: Currency + required: true + type: String + iBan: + description: The international bank account number of the account. Often used when making or receiving international payments + displayName: IBAN + required: false + type: String + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + validation: + information: + - details: Bank Account Posting Group with Nominal Account must exist + field: NominalCode + warnings: [] + overdraftLimit: + description: The pre-arranged overdraft limit of the account + displayName: Overdraft Limit + required: false + type: Number + validation: + information: + - details: Default value is 0 + field: OverdraftLimit + warnings: [] + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: false + type: String + validation: + information: + - details: Must have a length between 0 and 20 characters + field: SortCode + warnings: [] + required: true + type: Object + Exact (Netherlands): + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: true + type: String + validation: + information: [] + warnings: + - details: Should not exceed the maximum length of 14 characters if the specified currency is GBP. + field: AccountNumber + currency: + description: The currency of the bank account + displayName: Currency + required: false + type: String + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must be 6 characters long if the specified currency is GBP. + field: SortCode + - details: Must be provided if the specified currency is GBP. + field: SortCode + required: true + type: Object + Exact (UK): + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: true + type: String + validation: + information: [] + warnings: + - details: Should not exceed the maximum length of 14 characters if the specified currency is GBP. + field: AccountNumber + currency: + description: The currency of the bank account + displayName: Currency + required: false + type: String + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must be 6 characters long if the specified currency is GBP. + field: SortCode + - details: Must be provided if the specified currency is GBP. + field: SortCode + required: true + type: Object + FreeAgent: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: false + type: String + balance: + description: The balance of the bank account + displayName: Balance + required: false + type: Number + validation: + information: + - details: The opening balance, in the account currency + field: Balance + warnings: [] + currency: + description: The currency of the bank account + displayName: Currency + options: + - displayName: AED + required: false + type: String + value: AED + - displayName: AMD + required: false + type: String + value: AMD + - displayName: AOA + required: false + type: String + value: AOA + - displayName: ARS + required: false + type: String + value: ARS + - displayName: AUD + required: false + type: String + value: AUD + - displayName: AWG + required: false + type: String + value: AWG + - displayName: AZN + required: false + type: String + value: AZN + - displayName: BBD + required: false + type: String + value: BBD + - displayName: BDT + required: false + type: String + value: BDT + - displayName: BGN + required: false + type: String + value: BGN + - displayName: BRL + required: false + type: String + value: BRL + - displayName: BWP + required: false + type: String + value: BWP + - displayName: CAD + required: false + type: String + value: CAD + - displayName: CHF + required: false + type: String + value: CHF + - displayName: CLP + required: false + type: String + value: CLP + - displayName: CNY + required: false + type: String + value: CNY + - displayName: COP + required: false + type: String + value: COP + - displayName: CRC + required: false + type: String + value: CRC + - displayName: CUC + required: false + type: String + value: CUC + - displayName: CUP + required: false + type: String + value: CUP + - displayName: CZK + required: false + type: String + value: CZK + - displayName: DKK + required: false + type: String + value: DKK + - displayName: DOP + required: false + type: String + value: DOP + - displayName: EGP + required: false + type: String + value: EGP + - displayName: EUR + required: false + type: String + value: EUR + - displayName: FJD + required: false + type: String + value: FJD + - displayName: GBP + required: false + type: String + value: GBP + - displayName: GEL + required: false + type: String + value: GEL + - displayName: GHS + required: false + type: String + value: GHS + - displayName: GTQ + required: false + type: String + value: GTQ + - displayName: GYD + required: false + type: String + value: GYD + - displayName: HKD + required: false + type: String + value: HKD + - displayName: HNL + required: false + type: String + value: HNL + - displayName: HRK + required: false + type: String + value: HRK + - displayName: HUF + required: false + type: String + value: HUF + - displayName: IDR + required: false + type: String + value: IDR + - displayName: ILS + required: false + type: String + value: ILS + - displayName: INR + required: false + type: String + value: INR + - displayName: ISK + required: false + type: String + value: ISK + - displayName: JMD + required: false + type: String + value: JMD + - displayName: JPY + required: false + type: String + value: JPY + - displayName: KES + required: false + type: String + value: KES + - displayName: KRW + required: false + type: String + value: KRW + - displayName: KWD + required: false + type: String + value: KWD + - displayName: KYD + required: false + type: String + value: KYD + - displayName: KZT + required: false + type: String + value: KZT + - displayName: LAK + required: false + type: String + value: LAK + - displayName: LBP + required: false + type: String + value: LBP + - displayName: LKR + required: false + type: String + value: LKR + - displayName: LTL + required: false + type: String + value: LTL + - displayName: LVL + required: false + type: String + value: LVL + - displayName: MAD + required: false + type: String + value: MAD + - displayName: MDL + required: false + type: String + value: MDL + - displayName: MGA + required: false + type: String + value: MGA + - displayName: MUR + required: false + type: String + value: MUR + - displayName: MVR + required: false + type: String + value: MVR + - displayName: MWK + required: false + type: String + value: MWK + - displayName: MXN + required: false + type: String + value: MXN + - displayName: MYR + required: false + type: String + value: MYR + - displayName: MZN + required: false + type: String + value: MZN + - displayName: NAD + required: false + type: String + value: NAD + - displayName: NGN + required: false + type: String + value: NGN + - displayName: NOK + required: false + type: String + value: NOK + - displayName: NPR + required: false + type: String + value: NPR + - displayName: NZD + required: false + type: String + value: NZD + - displayName: OMR + required: false + type: String + value: OMR + - displayName: PEN + required: false + type: String + value: PEN + - displayName: PHP + required: false + type: String + value: PHP + - displayName: PKR + required: false + type: String + value: PKR + - displayName: PLN + required: false + type: String + value: PLN + - displayName: QAR + required: false + type: String + value: QAR + - displayName: RON + required: false + type: String + value: RON + - displayName: RSD + required: false + type: String + value: RSD + - displayName: RUB + required: false + type: String + value: RUB + - displayName: RWF + required: false + type: String + value: RWF + - displayName: SAR + required: false + type: String + value: SAR + - displayName: SCR + required: false + type: String + value: SCR + - displayName: SEK + required: false + type: String + value: SEK + - displayName: SGD + required: false + type: String + value: SGD + - displayName: THB + required: false + type: String + value: THB + - displayName: TND + required: false + type: String + value: TND + - displayName: TRY + required: false + type: String + value: TRY + - displayName: TTD + required: false + type: String + value: TTD + - displayName: TWD + required: false + type: String + value: TWD + - displayName: TZS + required: false + type: String + value: TZS + - displayName: UAH + required: false + type: String + value: UAH + - displayName: UGX + required: false + type: String + value: UGX + - displayName: USD + required: false + type: String + value: USD + - displayName: UYU + required: false + type: String + value: UYU + - displayName: VEF + required: false + type: String + value: VEF + - displayName: VND + required: false + type: String + value: VND + - displayName: VUV + required: false + type: String + value: VUV + - displayName: XAF + required: false + type: String + value: XAF + - displayName: XCD + required: false + type: String + value: XCD + - displayName: XOF + required: false + type: String + value: XOF + - displayName: ZAR + required: false + type: String + value: ZAR + - displayName: ZMK + required: false + type: String + value: ZMK + required: true + type: String + iBan: + description: The international bank account number of the account. Often used when making or receiving international payments + displayName: IBAN + required: false + type: String + institution: + description: The institution of the bank account + displayName: Institution + required: false + type: String + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 0 and 8 characters + field: SortCode + required: true + type: Object + KashFlow: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: Name of the bank account as it appears in Kashflow. + displayName: Account Name + required: true + type: String + balance: + description: The opening balance, in the account currency. + displayName: Balance + required: false + type: Number + currency: + description: The currency of the bank account. + displayName: Currency + required: true + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: AccountName + balance: + description: The balance of the bank account + displayName: Balance + required: false + type: Number + currency: + description: The currency of the bank account + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the base currency of the QuickBooks Desktop company + field: Currency + warnings: + - details: The currency must match the base currency of the QuickBooks Desktop company unless the FullyQualifiedCategory is 'Asset.AccountsReceivable','Liability.AccountsPayable' or 'Liability.CreditCard' + field: Currency + - details: Must be a three letter ISO code that matches an existing active currency in the QuickBooks Desktop company + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 7 characters. + field: NominalCode + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: Name of account as it appears in the chart of accounts or general ledger. + displayName: Account Name + required: true + type: String + accountNumber: + description: User-defined account number to help the user in identifying the account within the chart-of-accounts and in deciding what should be posted to the account. + displayName: Account Number + required: true + type: String + currency: + description: Currency of the bank account. + displayName: Currency + required: true + type: String + required: true + type: Object + Sage Business Cloud Accounting: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountName + - details: Should not be longer than 50 characters. + field: AccountName + warnings: [] + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: false + type: String + validation: + information: + - details: Should not be longer than 25 characters. + field: AccountNumber + warnings: [] + currency: + description: The currency of the bank account + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + - details: Must match the company's base currency. + field: Currency + warnings: [] + iBan: + description: The international bank account number of the account. Often used when making or receiving international payments + displayName: IBAN + required: false + type: String + validation: + information: + - details: Should be in the international bank account number format. + field: IBan + warnings: [] + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + validation: + information: + - details: Should be a number between 1 and 99999999. + field: NominalCode + warnings: [] + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: false + type: String + validation: + information: + - details: Should be a 6 digit number. + field: SortCode + warnings: [] + required: true + type: Object + Sandbox: + value: + description: An account that bank transactions may be recorded against + displayName: Bank Account + properties: + accountName: + description: The name of the bank account in the originating system + displayName: Name + required: true + type: String + accountNumber: + description: The account number for the bank account + displayName: Account Number + required: true + type: String + accountType: + description: The type of account + displayName: Account Type + required: true + type: String + availableBalance: + description: The available balance of the bank account + displayName: Available Balance + required: true + type: Number + balance: + description: The balance of the bank account + displayName: Balance + required: true + type: Number + currency: + description: The currency of the bank account + displayName: Currency + required: true + type: String + iBan: + description: The international bank account number of the account. Often used when making or receiving international payments + displayName: IBAN + required: true + type: String + institution: + description: The institution of the bank account + displayName: Institution + required: true + type: String + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + overdraftLimit: + description: The pre-arranged overdraft limit of the account + displayName: Overdraft Limit + required: true + type: Number + sortCode: + description: The sort code for the bank account + displayName: Sort Code + required: true + type: String + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update bank account model + tags: + - Bank accounts + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/bankAccounts/{accountId}/bankTransactions": + get: + description: Gets the options of pushing bank account transactions. + operationId: get-create-bank-account-model + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/paths/~1companies~1%7BcompanyId%7D~1connections~1%7BconnectionId%7D~1data~1bankAccounts~1%7BaccountId%7D~1bankTransactions/get/parameters/2" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOption" + description: Success + summary: List push options for bank account bank transactions + tags: + - Bank account transactions + x-extension-1: null + "/companies/{companyId}/connections/{connectionId}/options/billCreditNotes": + get: + description: |- + Get create/update bill credit note model. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=billCreditNotes) for integrations that support creating and updating bill credit notes. + operationId: get-create-update-billCreditNotes-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid currency code + field: Currency + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Either AccountRef or ItemRef should be specified. If AccountRef is chosen, ID must be specified + field: AccountRef.Id + required: false + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Either AccountRef or ItemRef should be specified. If ItemRef is chosen, ID must be specified + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be positive + field: LineItems.Quantity + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: [] + warnings: + - details: Must be positive + field: LineItems + note: + description: Note about the credit note + displayName: Note + required: true + type: String + validation: + information: [] + warnings: + - details: Vendor Credit Memo Number must be specified in this field + field: Note + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Draft + required: false + type: Array + value: Draft + - displayName: Submitted + required: false + type: Array + value: Submitted + - displayName: Void + required: false + type: Array + value: Void + required: true + type: String + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + FreeAgent: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + allocatedOnDate: + description: The date the credit note was allocated + displayName: Allocated On Date + required: true + type: DateTime + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: true + type: String + currency: + description: Currency of the credit note + displayName: Currency + options: + - displayName: AED + required: false + type: String + value: AED + - displayName: AMD + required: false + type: String + value: AMD + - displayName: AOA + required: false + type: String + value: AOA + - displayName: ARS + required: false + type: String + value: ARS + - displayName: AUD + required: false + type: String + value: AUD + - displayName: AWG + required: false + type: String + value: AWG + - displayName: AZN + required: false + type: String + value: AZN + - displayName: BBD + required: false + type: String + value: BBD + - displayName: BDT + required: false + type: String + value: BDT + - displayName: BGN + required: false + type: String + value: BGN + - displayName: BRL + required: false + type: String + value: BRL + - displayName: BWP + required: false + type: String + value: BWP + - displayName: CAD + required: false + type: String + value: CAD + - displayName: CHF + required: false + type: String + value: CHF + - displayName: CLP + required: false + type: String + value: CLP + - displayName: CNY + required: false + type: String + value: CNY + - displayName: COP + required: false + type: String + value: COP + - displayName: CRC + required: false + type: String + value: CRC + - displayName: CUC + required: false + type: String + value: CUC + - displayName: CUP + required: false + type: String + value: CUP + - displayName: CZK + required: false + type: String + value: CZK + - displayName: DKK + required: false + type: String + value: DKK + - displayName: DOP + required: false + type: String + value: DOP + - displayName: EGP + required: false + type: String + value: EGP + - displayName: EUR + required: false + type: String + value: EUR + - displayName: FJD + required: false + type: String + value: FJD + - displayName: GBP + required: false + type: String + value: GBP + - displayName: GEL + required: false + type: String + value: GEL + - displayName: GHS + required: false + type: String + value: GHS + - displayName: GTQ + required: false + type: String + value: GTQ + - displayName: GYD + required: false + type: String + value: GYD + - displayName: HKD + required: false + type: String + value: HKD + - displayName: HNL + required: false + type: String + value: HNL + - displayName: HRK + required: false + type: String + value: HRK + - displayName: HUF + required: false + type: String + value: HUF + - displayName: IDR + required: false + type: String + value: IDR + - displayName: ILS + required: false + type: String + value: ILS + - displayName: INR + required: false + type: String + value: INR + - displayName: ISK + required: false + type: String + value: ISK + - displayName: JMD + required: false + type: String + value: JMD + - displayName: JPY + required: false + type: String + value: JPY + - displayName: KES + required: false + type: String + value: KES + - displayName: KRW + required: false + type: String + value: KRW + - displayName: KWD + required: false + type: String + value: KWD + - displayName: KYD + required: false + type: String + value: KYD + - displayName: KZT + required: false + type: String + value: KZT + - displayName: LAK + required: false + type: String + value: LAK + - displayName: LBP + required: false + type: String + value: LBP + - displayName: LKR + required: false + type: String + value: LKR + - displayName: LTL + required: false + type: String + value: LTL + - displayName: LVL + required: false + type: String + value: LVL + - displayName: MAD + required: false + type: String + value: MAD + - displayName: MDL + required: false + type: String + value: MDL + - displayName: MGA + required: false + type: String + value: MGA + - displayName: MUR + required: false + type: String + value: MUR + - displayName: MVR + required: false + type: String + value: MVR + - displayName: MWK + required: false + type: String + value: MWK + - displayName: MXN + required: false + type: String + value: MXN + - displayName: MYR + required: false + type: String + value: MYR + - displayName: MZN + required: false + type: String + value: MZN + - displayName: NAD + required: false + type: String + value: NAD + - displayName: NGN + required: false + type: String + value: NGN + - displayName: NOK + required: false + type: String + value: NOK + - displayName: NPR + required: false + type: String + value: NPR + - displayName: NZD + required: false + type: String + value: NZD + - displayName: OMR + required: false + type: String + value: OMR + - displayName: PEN + required: false + type: String + value: PEN + - displayName: PHP + required: false + type: String + value: PHP + - displayName: PKR + required: false + type: String + value: PKR + - displayName: PLN + required: false + type: String + value: PLN + - displayName: QAR + required: false + type: String + value: QAR + - displayName: RON + required: false + type: String + value: RON + - displayName: RSD + required: false + type: String + value: RSD + - displayName: RUB + required: false + type: String + value: RUB + - displayName: RWF + required: false + type: String + value: RWF + - displayName: SAR + required: false + type: String + value: SAR + - displayName: SCR + required: false + type: String + value: SCR + - displayName: SEK + required: false + type: String + value: SEK + - displayName: SGD + required: false + type: String + value: SGD + - displayName: THB + required: false + type: String + value: THB + - displayName: TND + required: false + type: String + value: TND + - displayName: TRY + required: false + type: String + value: TRY + - displayName: TTD + required: false + type: String + value: TTD + - displayName: TWD + required: false + type: String + value: TWD + - displayName: TZS + required: false + type: String + value: TZS + - displayName: UAH + required: false + type: String + value: UAH + - displayName: UGX + required: false + type: String + value: UGX + - displayName: USD + required: false + type: String + value: USD + - displayName: UYU + required: false + type: String + value: UYU + - displayName: VEF + required: false + type: String + value: VEF + - displayName: VND + required: false + type: String + value: VND + - displayName: VUV + required: false + type: String + value: VUV + - displayName: XAF + required: false + type: String + value: XAF + - displayName: XCD + required: false + type: String + value: XCD + - displayName: XOF + required: false + type: String + value: XOF + - displayName: ZAR + required: false + type: String + value: ZAR + - displayName: ZMK + required: false + type: String + value: ZMK + required: false + type: String + validation: + information: + - details: If not specified, defaults to the company's native currency + field: Currency + warnings: [] + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Amount of sales tax for the BillCreditNoteLineItem in company's native currency. + field: LineItems.TaxAmount + warnings: + - details: Must be positive for bill items and negative for credit items. If not specified, defaults to the tax correct tax rate amount for the category of the bill. + field: LineItems.TaxAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Up to a maximum of 40 line items may be specified + field: LineItems + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than 0 and must be equal to the sum of the line item total amounts. + field: TotalAmount + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than 0 and must be equal to the sum of the line item tax amounts. + field: TotalTaxAmount + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: + - details: Must not be greater than 225 characters long. + field: LineItems.Description + warnings: [] + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.SubTotal + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.TaxAmount + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.TotalAmount + - details: Must be greater than zero. + field: LineItems.TotalAmount + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + remainingCredit: + description: Unused balance of total amount originally raised + displayName: Remaining Credit + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: RemainingCredit + subTotal: + description: The amount of the credit note, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: SubTotal + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: SupplierRef + warnings: [] + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalAmount + - details: Must be greater than zero. + field: TotalAmount + totalDiscount: + description: The value, in the given credit note currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalDiscount + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalTaxAmount + required: true + type: Object + Oracle NetSuite: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + required: true + type: String + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.UnitAmount + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Desktop: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the supplier. + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the supplier. + field: Currency + - details: Can only be set if the QuickBooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Account type must be Asset, Liability or Expense and not Accounts Payable + field: LineItems.AccountRef + warnings: + - details: Can't include both AccountRef and ItemRef + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item type. + field: ItemRef.Id + required: true + type: Object + validation: + information: + - details: Item type must not be Discount or Sale-Tax items + field: LineItems.ItemRef + warnings: + - details: Can't include both AccountRef and ItemRef + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + validation: + information: + - details: Must match quantity * unit amount of line + field: LineItems.SubTotal + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot be mapped directly into QuickBooks Desktop and will only be used for validation purposes + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Only valid for UK or CA versions of QuickBooks Desktop with VAT enabled + field: TaxRateRef.Id + - details: Must match the ID of an existing tax rate + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must match subtotal + tax amount of line + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: Note + paymentAllocations: + description: A collection of payments that are allocated to (i.e. spend) the credit note + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: If set, must match issue date on the bill credit note + field: Allocation.AllocatedOnDate + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: If set, must match currency on the bill credit note + field: Allocation.Currency + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: If set, must match currency rate on the bill credit note + field: Allocation.CurrencyRate + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match total amount on the bill credit note + field: Allocation.TotalAmount + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing credit card account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: " Account type must be of type Credit Card" + field: Payment.AccountRef + warnings: [] + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: $ set, must match currency on the {topLevelItem} + field: Payment.Currency + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: If set, must match currency rate on the bill credit note + field: Payment.CurrencyRate + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + validation: + information: [] + warnings: + - details: Must match issue date on the bill credit note + field: Payment.PaidOnDate + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: " Must match total amount on the bill credit note" + field: Payment.TotalAmount + required: true + type: Object + required: false + type: Array + validation: + information: + - details: If a payment allocation is provided, a credit card credit will created in QuickBooksDesktop, if left as null or empty, a {topLevelItem} will be created + field: PaymentAllocations + warnings: + - details: A maximum of one payment allocation may be provided per bill credit note + field: PaymentAllocations + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + - displayName: Paid + required: false + type: String + value: Paid + - displayName: Void + required: false + type: String + value: Void + required: true + type: String + validation: + information: + - details: If a bill credit note is pushed with a status of void, then all the amounts in the bill credit note must be 0 + field: Status + - details: If a bill credit note is pushed without payment allocations, then the status must be Submitted, if pushed with payment allocations, then the status must be paid + field: Status + warnings: + - details: If a bill credit note is pushed with a total amount of 0, then the status must be Paid or Void + field: Status + subTotal: + description: The amount of the credit note, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the totalAmount - taxAmount + field: SubTotal + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier + field: SupplierRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: If a bill credit note is pushed with a total amount of 0, it will automatically be marked as paid in QuickBooks Desktop + field: TotalAmount + warnings: + - details: Must match the sum of line items ((quantity * unit price) - discount + tax) + field: TotalAmount + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot be mapped directly into QuickBooks Desktop and will only be used for validation purposes + field: TotalTaxAmount + - details: Must match sum of total of tax from the line items + field: TotalTaxAmount + required: true + type: Object + QuickBooks Online: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Required if the expense line is account based. If AccountRef is specified, ItemRef must be null. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: Required if the expense line is item based. If ItemRef is specified, AccountRef must be null. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments that are allocated to (i.e. spend) the credit note + displayName: Payment Allocations + required: false + type: Array + validation: + information: [] + warnings: + - details: Payment Allocations are no longer valid for BillCreditNotes and must not be provided, use the DirectCost data type to push credit card credits. + field: PaymentAllocations + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + - displayName: Paid + required: false + type: String + value: Paid + required: true + type: String + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Required if the expense line is account based. If AccountRef is specified, ItemRef must be null. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: Required if the expense line is item based. If ItemRef is specified, AccountRef must be null. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments that are allocated to (i.e. spend) the credit note + displayName: Payment Allocations + required: false + type: Array + validation: + information: [] + warnings: + - details: Payment Allocations are no longer valid for BillCreditNotes and must not be provided, use the DirectCost data type to push credit card credits. + field: PaymentAllocations + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + - displayName: Paid + required: false + type: String + value: Paid + required: true + type: String + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + Sage 50 (UK): + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + billCreditNoteNumber: + description: The reference number for this bill credit note + displayName: Bill Credit Note Number + required: true + type: String + currency: + description: The currency in which the bill credit note is issued. + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: This must match the supplier's default currency. + field: currency + issueDate: + description: Date when the bill credit note was issued. + displayName: Date + required: true + type: DateTime + lineItems: + description: Line items of the bill credit note. + displayName: Line Items + properties: + accountRef: + description: Identifier for the account. + displayName: Account Reference + properties: + id: + description: Identifier of the account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: accountRef.id + required: true + type: Object + description: + description: Description of the bill credit note line item. + displayName: Description + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 60 characters. + field: lineItems.description + taxAmount: + description: Tax of the bill credit note line item. + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Tax rate reference of a bill credit note line item. + displayName: Tax Rate Reference + properties: + id: + description: ID of the tax rate. + displayName: Tax Rate Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: taxRateRef.id + required: true + type: Object + totalAmount: + description: The total amount of the bill credit note line item, inclusive of the tax amount. + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: Tracking categories for the line item + displayName: Tracking Categories + properties: + id: + description: Prefixed identifier for tracking category e.g. project_{x}, department_{x}, costcode_{x} + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Cost codes assigned with costcode_{x} must exist in Sage50 and must be assigned in conjunction with a project + field: trackingCategoryRefs.id + - details: Projects assigned with project_{x} must exist in Sage50 and must be assigned in conjunction with a cost code + field: trackingCategoryRefs.id + - details: Departments assigned with department_{x} must exist in Sage50 + field: trackingCategoryRefs.id + required: false + type: Array + required: true + type: Array + note: + description: To be used for any additional information associated with the bill credit note line item. + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Maximum 60 characters + field: note + status: + description: The status of the bill credit note + displayName: Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + supplierRef: + description: Supplier providing the bill credit note. + displayName: Supplier + properties: + id: + description: Identifier of the supplier. + displayName: Supplier Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier and have a max length of 8 characters. + field: supplierRef.id + required: true + type: Object + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: + - details: Should not be longer than 25 characters. + field: BillCreditNoteNumber + warnings: [] + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: If supplied, must match the currency of the supplier. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Should not be longer than 2000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the total of the line including tax. + field: LineItems.TotalAmount + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + - details: The supplier must be in the same location as the company. + field: SupplierRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the sum of all line item total amounts. + field: TotalAmount + warnings: [] + required: true + type: Object + Sage Intacct: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + allocatedOnDate: + description: The date the credit note was allocated + displayName: Allocated On Date + required: false + type: DateTime + currency: + description: Currency of the credit note + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + - displayName: Canadian Dollar + required: false + type: String + value: CAD + - displayName: Pound Sterling + required: false + type: String + value: GBP + - displayName: US Dollar + required: false + type: String + value: USD + - displayName: Rand + required: false + type: String + value: ZAR + required: false + type: String + validation: + information: + - details: Must be provided if CurrencyRate is set. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: + - details: Must contain no more than 1000 characters. + field: LineItems.Description + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Must not be negative. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be an existing tax rate in Sage Intacct. + field: TaxRateRef.Id + warnings: [] + required: false + type: Object + validation: + information: + - details: Must be provided when TaxAmount is set. + field: LineItems.TaxRateRef + warnings: [] + trackingCategoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must not be negative. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must contain at least one line item. + field: LineItems + warnings: [] + note: + description: Note about the credit note + displayName: Note + required: false + type: String + validation: + information: + - details: Must contain no more than 1000 characters. + field: Note + warnings: [] + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + required: false + type: String + validation: + information: + - details: If not specified will default to Submitted. + field: Status + warnings: [] + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + Sandbox: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + allocatedOnDate: + description: The date the credit note was allocated + displayName: Allocated On Date + required: true + type: DateTime + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: true + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given credit note currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + customerRef: + description: Reference to the customer this line item is being tracked against + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + isBilledTo: + description: The type of item this line item is billed to. + displayName: Is Billed To + required: true + type: String + isRebilledTo: + description: The type of item this line item is billed to + displayName: Is Rebilled To + required: true + type: String + projectRef: + description: Reference to the project this line item is being tracked against + displayName: Project Reference + properties: + id: + description: The reference identifier for the Project + displayName: Identifier + required: true + type: String + name: + description: The name of the Project referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Note about the credit note + displayName: Note + required: true + type: String + paymentAllocations: + description: A collection of payments that are allocated to (i.e. spend) the credit note + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + remainingCredit: + description: Unused balance of total amount originally raised + displayName: Remaining Credit + required: true + type: Number + status: + description: The current state of a credit note + displayName: Credit Note Status + required: true + type: String + subTotal: + description: The amount of the credit note, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + supplierName: + description: The name of the supplier referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + totalDiscount: + description: The value, in the given credit note currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: true + type: Number + withholdingTax: + description: A collection of tax deductions + displayName: Withholding Tax + properties: + amount: + description: Deduction amount + displayName: Amount + required: true + type: Number + name: + description: Name of the deduction + displayName: Name + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: A bill credit note can be thought of as a voucher issued by a supplier. It can be applied against one or multiple bills to reduce their balance. + displayName: Accounts Payable Credit Note + properties: + billCreditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: + - details: Must not be longer than 225 characters long. + field: BillCreditNoteNumber + warnings: [] + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + - displayName: Paid + required: false + type: String + value: Paid + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + supplierRef: + description: Reference to the supplier the credit note has been issued by + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must be a valid GUID. + field: SupplierRef.Id + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: SupplierRef + warnings: [] + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must equal the sum of the link items amount. + field: TotalAmount + warnings: + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update bill credit note model + tags: + - Bill credit notes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/billPayments": + get: + description: |- + Get create bill payment model. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=billPayments) for integrations that support creating and deleting bill payments. + operationId: get-create-billPayments-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: An account ID must be provided if not allocating against bill + field: AccountRef.Id + required: false + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid currency code + field: Currency + lines: + description: A collection of payment lines + displayName: Lines + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + validation: + information: [] + warnings: + - details: AllocatedOnDate must be specified and be later than the issue date of the bill + field: Lines.AllocatedOnDate + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + FreeAgent: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must match the sum of the link amounts. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Bill Credit Note + required: false + type: String + value: CreditNote + - displayName: Other + required: false + type: String + value: Other + required: true + type: String + required: true + type: Array + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line may be specified + field: Lines + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line amounts. + field: TotalAmount + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Links.Amount + warnings: + - details: Precision must be maximum of two decimal places. + field: Links.Amount + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Id + warnings: [] + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - required: false + type: String + value: Bill + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines.Links + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines + warnings: [] + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not be greater than 8 characters long. + field: Reference + warnings: [] + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must be a valid GUID. + field: SupplierRef.Id + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: SupplierRef + warnings: [] + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must equal the sum of the link items amount. + field: TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalAmount + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + Oracle NetSuite: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account of type 'Bank' OR type 'Credit Card' + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: If the currency is set make sure it's the same as the 'Bill' and/or 'VendorCredit' currency + field: Currency + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Ensure the status of the linked bill is either 'PartiallyPaid' or 'Submitted' + field: Links.Id + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Bill Credit Note + required: false + type: String + value: CreditNote + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: + - details: This field can be used to provide a tracking category id (Location only) + field: Reference + warnings: + - details: The id format should be 'location-' + field: Reference + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Desktop: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: "If an ID which corresponds to a bank account is provided, a 'bill payment check' will be added to Quickbooks Desktop, If an ID which corresponds to a credit card account is provided, a 'bill payment credit card' will be added Quickbooks Desktop. " + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing Bank or Credit Card account. + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the supplier + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the supplier + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Amount plus the sum of amounts in the links must equal 0 + field: Lines.Amount + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Credit Note + required: false + type: String + value: CreditNote + required: true + type: String + validation: + information: [] + warnings: + - details: Exactly 1 link with type 'Bill' must be specified per line + field: Links.Type + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of amounts in the lines + field: TotalAmount + required: true + type: Object + QuickBooks Online: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: + - details: Required if TotalAmount is greater than zero. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Amount and sum of Links must sum to zero. + field: Lines.Amount + links: + description: A collection of linked transactions + displayName: Links + properties: + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Credit Note + required: false + type: String + value: CreditNote + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + paymentMethodRef: + description: The method of payment + displayName: Payment Method Reference + required: false + type: Object + validation: + information: [] + warnings: + - details: If provided it will be ignored. + field: PaymentMethodRef + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be the ID of the Supplier associated with the Bill or Credit Note. + field: SupplierRef + warnings: [] + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: + - details: Required if TotalAmount is greater than zero. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Amount and sum of Links must sum to zero. + field: Lines.Amount + links: + description: A collection of linked transactions + displayName: Links + properties: + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Credit Note + required: false + type: String + value: CreditNote + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + paymentMethodRef: + description: The method of payment + displayName: Payment Method Reference + required: false + type: Object + validation: + information: [] + warnings: + - details: If provided it will be ignored. + field: PaymentMethodRef + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be the ID of the Supplier associated with the Bill or Credit Note. + field: SupplierRef + warnings: [] + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Sage 50 (UK): + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: The bank account to pay this bill from. + displayName: Bank Account + properties: + id: + description: Nominal code of the bank account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account and have a max length of 8 characters. + field: accountRef.id + required: true + type: Object + date: + description: The date this payment was issued. + displayName: Issue Date + required: true + type: Number + lines: + description: Line items of the payment. + displayName: Line Items + properties: + amount: + description: The amount of this line item + displayName: Amount + required: true + type: Number + validation: + information: + - details: this must equal the negative of the sum of the link amounts + warnings: [] + links: + description: Links to the bills being paid. + displayName: Links + properties: + amount: + description: The amount to be added to the value of the bill + displayName: Amount + required: true + type: Number + validation: + information: + - details: When paying off a bill, this value will be negative + warnings: [] + id: + description: The ID of the bill to pay + displayName: Bill Id + required: true + type: String + type: + description: The type of the item to be paid + displayName: Payment Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + required: true + type: String + required: true + type: Array + required: true + type: Array + validation: + information: + - details: Sage 50 only supports one line item per bill payment so all lines will be merged together in the response. + warnings: [] + note: + description: A description of the payment. + displayName: Note + required: false + type: Number + reference: + description: The user reference for this bill payment. + displayName: Reference + required: false + type: Number + supplierRef: + description: Supplier to be paid. + displayName: Supplier + properties: + id: + description: Identifier of the supplier. + displayName: Supplier Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier and have a max length of 8 characters. + field: supplierRef.id + required: true + type: Object + totalAmount: + description: The total amount being paid to the supplier. + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: This must equal the sum of the line amounts + warnings: [] + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Required unless the BillPayment is only allocating a Credit Note. + field: AccountRef + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: + - details: If supplied, must match the currency of the supplier. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Links.Amount + warnings: + - details: Must be greater than zero except when Link Type is Bill. + field: Links.Amount + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Id + warnings: [] + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: PaymentOnAccount + required: false + type: String + value: PaymentOnAccount + - displayName: Refund + required: false + type: String + value: Refund + - displayName: CreditNote + required: false + type: String + value: CreditNote + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines.Links + warnings: [] + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + validation: + information: + - details: Should not be longer than 25 characters. + field: Note + warnings: [] + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Must be zero when allocating against Bills using a Credit Note only. + field: TotalAmount + - details: Must equal the sum of the link items amount. + field: TotalAmount + required: true + type: Object + Sage Intacct: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must be an account of type BankAccount and compatible with the type of PaymentMethodRef + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + - displayName: Canadian Dollar + required: false + type: String + value: CAD + - displayName: Pound Sterling + required: false + type: String + value: GBP + - displayName: US Dollar + required: false + type: String + value: USD + - displayName: Rand + required: false + type: String + value: ZAR + required: false + type: String + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must not be a negative amount + field: Lines.Amount + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: CreditNote + required: false + type: String + value: CreditNote + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 1000 characters + field: Note + paymentMethodRef: + description: The method of payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + options: + - displayName: Credit Card + required: false + type: String + value: "3" + - displayName: EFT + required: false + type: String + value: "5" + - displayName: Cash + required: false + type: String + value: "6" + required: true + type: String + required: true + type: Object + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be a positive amount + field: TotalAmount + required: true + type: Object + Sandbox: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + currencyRate: + description: The exchange rate between the currency of the payment and the currency of the linked transaction + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + required: true + type: String + required: true + type: Array + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Any additional text based information associated with the payment + displayName: Note + required: true + type: String + paymentMethodRef: + description: The method of payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + required: true + type: String + name: + description: The name of the payment method referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + reference: + description: A user friendly reference for the payment + displayName: Reference + required: true + type: String + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + supplierName: + description: The name of the supplier referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Xero: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + validation: + information: + - details: Must be provided if paying a bill from a Bank Account. + field: AccountRef.Id + warnings: [] + required: false + type: Object + validation: + information: + - details: Must be provided if paying a bill from a Bank Account. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be the company's base currency when pushing a batch payment. + field: Currency + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Links.Amount + warnings: [] + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Bill and Bill Credit Note ID must be provided in order to allocate a Bill Credit Note to a Bill. + field: Links.Id + - details: Must be provided. + field: Links.Id + warnings: + - details: Must be a valid GUID. + field: Links.Id + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Bill Payment + required: false + type: String + value: BillPayment + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: When a single line is provided, must only contain a single Link of type Bill, CreditNote or BillPayment, or two Links of type CreditNote and Bill for a credit note allocation. + field: Lines.Links + - details: When more than one line is provided, it must only contain a single Link of type Bill. + field: Lines.Links + warnings: [] + required: true + type: Array + validation: + information: + - details: When more than one line is provided, a batch payment will be created. + field: Lines + warnings: [] + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Must match the sum of line amounts. + field: TotalAmount + required: true + type: Object + Zoho Books: + value: + description: A bill payment represents an allocation of transactions across an 'accounts payable' account (supplier) + displayName: BillPayment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided when making a payment to an invoice and/or a payment on account + field: AccountRef + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must match supplier's currency + field: Currency + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be greater or equal to 0 + field: CurrencyRate + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be less than 0 for links of type Bill and PaymentOnAccount or greater than 0 for links of type CreditNote + field: Links.Amount + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Bill + required: false + type: String + value: Bill + - displayName: PaymentOnAccount + required: false + type: String + value: PaymentOnAccount + - displayName: CreditNote + required: false + type: String + value: CreditNote + required: true + type: String + required: true + type: Array + validation: + information: [] + warnings: + - details: If using a bill credit note to pay a bill must contain 1 bill payment line link of type CreditNote and 1 bill payment line link of type Bill. Otherwise must contain at least 1 bill payment line linkof type Bill or PaymentOnAccount + field: Lines.Links + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain 1 bill payment line + field: Lines + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + supplierRef: + description: Reference to the supplier the payment has been sent to + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create bill payment model + tags: + - Bill payments + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/bills": + get: + description: |- + Get create/update bill model. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bills) for integrations that support creating and updating a bill. + operationId: get-create-update-bills-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Please ensure that the account posting setup for this account is valid before pushing + field: AccountRef.Id + - details: Either AccountRef or ItemRef should be specified. If AccountRef is chosen, ID must be specified + field: AccountRef.Id + required: false + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Either AccountRef or ItemRef should be specified. If ItemRef is chosen, ID must be specified + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be positive + field: LineItems.Quantity + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Every Tracking Category specified will be applied to every line item + field: CategoryRefs.Id + warnings: + - details: Must not be a parent Tracking Category. All Tracking Category specified must have different parent categories + field: CategoryRefs.Id + required: true + type: Array + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + required: true + type: Array + note: + description: Note about the bill + displayName: Note + required: true + type: String + validation: + information: [] + warnings: + - details: Supplier Invoice Number must be specified in this field + field: Note + status: + description: The current state of the bill + displayName: Bill Status + options: + - displayName: Draft + required: false + type: Array + value: Draft + - displayName: Void + required: false + type: Array + value: Void + - displayName: Open + required: false + type: Array + value: Open + required: true + type: String + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + FreeAgent: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + options: + - displayName: AED + required: false + type: String + value: AED + - displayName: AMD + required: false + type: String + value: AMD + - displayName: AOA + required: false + type: String + value: AOA + - displayName: ARS + required: false + type: String + value: ARS + - displayName: AUD + required: false + type: String + value: AUD + - displayName: AWG + required: false + type: String + value: AWG + - displayName: AZN + required: false + type: String + value: AZN + - displayName: BBD + required: false + type: String + value: BBD + - displayName: BDT + required: false + type: String + value: BDT + - displayName: BGN + required: false + type: String + value: BGN + - displayName: BRL + required: false + type: String + value: BRL + - displayName: BWP + required: false + type: String + value: BWP + - displayName: CAD + required: false + type: String + value: CAD + - displayName: CHF + required: false + type: String + value: CHF + - displayName: CLP + required: false + type: String + value: CLP + - displayName: CNY + required: false + type: String + value: CNY + - displayName: COP + required: false + type: String + value: COP + - displayName: CRC + required: false + type: String + value: CRC + - displayName: CUC + required: false + type: String + value: CUC + - displayName: CUP + required: false + type: String + value: CUP + - displayName: CZK + required: false + type: String + value: CZK + - displayName: DKK + required: false + type: String + value: DKK + - displayName: DOP + required: false + type: String + value: DOP + - displayName: EGP + required: false + type: String + value: EGP + - displayName: EUR + required: false + type: String + value: EUR + - displayName: FJD + required: false + type: String + value: FJD + - displayName: GBP + required: false + type: String + value: GBP + - displayName: GEL + required: false + type: String + value: GEL + - displayName: GHS + required: false + type: String + value: GHS + - displayName: GTQ + required: false + type: String + value: GTQ + - displayName: GYD + required: false + type: String + value: GYD + - displayName: HKD + required: false + type: String + value: HKD + - displayName: HNL + required: false + type: String + value: HNL + - displayName: HRK + required: false + type: String + value: HRK + - displayName: HUF + required: false + type: String + value: HUF + - displayName: IDR + required: false + type: String + value: IDR + - displayName: ILS + required: false + type: String + value: ILS + - displayName: INR + required: false + type: String + value: INR + - displayName: ISK + required: false + type: String + value: ISK + - displayName: JMD + required: false + type: String + value: JMD + - displayName: JPY + required: false + type: String + value: JPY + - displayName: KES + required: false + type: String + value: KES + - displayName: KRW + required: false + type: String + value: KRW + - displayName: KWD + required: false + type: String + value: KWD + - displayName: KYD + required: false + type: String + value: KYD + - displayName: KZT + required: false + type: String + value: KZT + - displayName: LAK + required: false + type: String + value: LAK + - displayName: LBP + required: false + type: String + value: LBP + - displayName: LKR + required: false + type: String + value: LKR + - displayName: LTL + required: false + type: String + value: LTL + - displayName: LVL + required: false + type: String + value: LVL + - displayName: MAD + required: false + type: String + value: MAD + - displayName: MDL + required: false + type: String + value: MDL + - displayName: MGA + required: false + type: String + value: MGA + - displayName: MUR + required: false + type: String + value: MUR + - displayName: MVR + required: false + type: String + value: MVR + - displayName: MWK + required: false + type: String + value: MWK + - displayName: MXN + required: false + type: String + value: MXN + - displayName: MYR + required: false + type: String + value: MYR + - displayName: MZN + required: false + type: String + value: MZN + - displayName: NAD + required: false + type: String + value: NAD + - displayName: NGN + required: false + type: String + value: NGN + - displayName: NOK + required: false + type: String + value: NOK + - displayName: NPR + required: false + type: String + value: NPR + - displayName: NZD + required: false + type: String + value: NZD + - displayName: OMR + required: false + type: String + value: OMR + - displayName: PEN + required: false + type: String + value: PEN + - displayName: PHP + required: false + type: String + value: PHP + - displayName: PKR + required: false + type: String + value: PKR + - displayName: PLN + required: false + type: String + value: PLN + - displayName: QAR + required: false + type: String + value: QAR + - displayName: RON + required: false + type: String + value: RON + - displayName: RSD + required: false + type: String + value: RSD + - displayName: RUB + required: false + type: String + value: RUB + - displayName: RWF + required: false + type: String + value: RWF + - displayName: SAR + required: false + type: String + value: SAR + - displayName: SCR + required: false + type: String + value: SCR + - displayName: SEK + required: false + type: String + value: SEK + - displayName: SGD + required: false + type: String + value: SGD + - displayName: THB + required: false + type: String + value: THB + - displayName: TND + required: false + type: String + value: TND + - displayName: TRY + required: false + type: String + value: TRY + - displayName: TTD + required: false + type: String + value: TTD + - displayName: TWD + required: false + type: String + value: TWD + - displayName: TZS + required: false + type: String + value: TZS + - displayName: UAH + required: false + type: String + value: UAH + - displayName: UGX + required: false + type: String + value: UGX + - displayName: USD + required: false + type: String + value: USD + - displayName: UYU + required: false + type: String + value: UYU + - displayName: VEF + required: false + type: String + value: VEF + - displayName: VND + required: false + type: String + value: VND + - displayName: VUV + required: false + type: String + value: VUV + - displayName: XAF + required: false + type: String + value: XAF + - displayName: XCD + required: false + type: String + value: XCD + - displayName: XOF + required: false + type: String + value: XOF + - displayName: ZAR + required: false + type: String + value: ZAR + - displayName: ZMK + required: false + type: String + value: ZMK + required: false + type: String + validation: + information: + - details: If not specified, defaults to the company's native currency + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Amount of sales tax for the BillLineItem in company's native currency. + field: LineItems.TaxAmount + warnings: + - details: Must be positive for bill items and negative for credit items. If not specified, defaults to the tax correct tax rate amount for the category of the bill. + field: LineItems.TaxAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain at least one line item and up to a maximum of 40 line items allowed. + field: LineItems + reference: + description: User friendly reference for the bill + displayName: Reference + required: true + type: String + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + taxAmount: + description: The total amount of tax on the bill + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than or equal to 0, less than or equal to the Bill.TotalAmount and equal to the total value of the bill item tax amounts. + field: TaxAmount + totalAmount: + description: The amount of the bill, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than or equal to 0 and must be equal to the total value of the bill item total amounts. + field: TotalAmount + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + amountDue: + description: The amount outstanding on the bill + displayName: Amount Due + required: false + type: Number + validation: + information: + - details: Must be at least zero and no more than that the total amount. + field: AmountDue + warnings: + - details: Precision must be maximum of two decimal places. + field: AmountDue + currency: + description: Currency of the bill + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must not be before the due date. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: [] + required: true + type: Object + validation: + information: [] + warnings: + - details: Must match the Inventory Item's AccountRef if supplied + field: LineItems.AccountRef + - details: Must be supplied except when an ItemRef is supplied + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: + - details: Must not be greater than 225 characters long. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.TaxRateRef + warnings: [] + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.TotalAmount + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.UnitAmount + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not be greater than 8 characters long. + field: Reference + warnings: [] + subTotal: + description: The total amount of the bill excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: SubTotal + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: SupplierRef + warnings: [] + taxAmount: + description: The total amount of tax on the bill + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: TaxAmount + totalAmount: + description: The amount of the bill, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalAmount + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + Oracle NetSuite: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + options: + - displayName: Open + required: false + type: String + value: Open + properties: + currency: + description: Currency of the bill + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: false + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: false + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + validation: + information: + - details: Should only be specified when pushing an expense + field: AccountRef.Id + warnings: [] + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: + - details: Should only be specified when pushing an item (not an expense) + field: ItemRef.Id + warnings: [] + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the bill + displayName: Note + required: false + type: String + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + status: + description: The current state of the bill + displayName: Bill Status + required: true + type: String + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Desktop: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the supplier + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the supplier + field: Currency + - details: Can only be set if the QuickBooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: false + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Account type must be Asset, Liability or Expense and not Accounts Payable + field: LineItems.AccountRef + warnings: + - details: Can't include both AccountRef and ItemRef + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item type. + field: ItemRef.Id + required: true + type: Object + validation: + information: + - details: Item type must not be Discount or Sale-Tax items + field: LineItems.ItemRef + warnings: + - details: Can't include both AccountRef and ItemRef + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + validation: + information: + - details: Must match quantity * unit amount of line + field: LineItems.SubTotal + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot be mapped directly into QuickBooks Desktop and will only be used for validation purposes + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Only valid for UK or CA versions of QuickBooks Desktop with VAT enabled + field: TaxRateRef.Id + - details: Must match the ID of an existing tax rate + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must match subtotal + tax amount of line + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the bill + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: Note + paymentAllocations: + description: A collection of payments allocated to the bill + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: If set, must match issue date on the bill + field: Allocation.AllocatedOnDate + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: If set, must match currency on the bill + field: Allocation.Currency + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: If set, must match currency rate on the bill + field: Allocation.CurrencyRate + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match total amount on the bill + field: Allocation.TotalAmount + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing credit card account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: " Account type must be of type Credit Card" + field: Payment.AccountRef + warnings: [] + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: $ set, must match currency on the {topLevelItem} + field: Payment.Currency + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: If set, must match currency rate on the bill + field: Payment.CurrencyRate + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + validation: + information: [] + warnings: + - details: Must match issue date on the bill + field: Payment.PaidOnDate + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: " Must match total amount on the bill" + field: Payment.TotalAmount + required: true + type: Object + required: false + type: Array + validation: + information: + - details: If a payment allocation is provided, a credit card charge will created in QuickBooksDesktop, if left as null or empty, a {topLevelItem} will be created + field: PaymentAllocations + warnings: + - details: A maximum of one payment allocation may be provided per bill + field: PaymentAllocations + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 20 characters. + field: Reference + status: + description: The current state of the bill + displayName: Bill Status + options: + - displayName: Open + required: false + type: String + value: Open + - displayName: Paid + required: false + type: String + value: Paid + - displayName: Void + required: false + type: String + value: Void + required: true + type: String + validation: + information: + - details: If a bill is pushed with a status of void, then all the amounts in the bill must be 0 + field: Status + - details: If a bill is pushed without payment allocations, then the status must be Open, if pushed with payment allocations, then the status must be paid + field: Status + warnings: + - details: If a bill is pushed with a total amount of 0, then the status must be Paid or Void + field: Status + subTotal: + description: The total amount of the bill excluding any taxes + displayName: Sub Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the totalAmount - taxAmount + field: SubTotal + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + taxAmount: + description: The total amount of tax on the bill + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot be mapped directly into QuickBooks Desktop and will only be used for validation purposes + field: TaxAmount + - details: Must match sum of total of tax from the line items + field: TaxAmount + totalAmount: + description: The amount of the bill, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: If a bill is pushed with a total amount of 0, it will automatically be marked as paid in QuickBooks Desktop + field: TotalAmount + warnings: + - details: Must match the sum of line items ((quantity * unit price) - discount + tax) + field: TotalAmount + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + options: + - displayName: USD + required: false + type: String + value: USD + required: true + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Required if the expense line is account based. If AccountRef is specified, ItemRef must be null. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: false + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: Required if the expense line is item based. If ItemRef is specified, AccountRef must be null. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used, or the tax rate must be unset. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + customerRef: + description: Reference to the customer this line item is being tracked against + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: false + type: String + required: false + type: Object + isRebilledTo: + description: The type of item this line item is billed to + displayName: Is Rebilled To + required: false + type: String + validation: + information: [] + warnings: + - details: Must be set to 'Customer' when Tracking.CustomerRef is supplied + field: Tracking.IsRebilledTo + required: false + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category and be of type DEPARTMENT or CLASS. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the bill + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the bill + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: false + type: Array + validation: + information: [] + warnings: + - details: Payment Allocations are no longer valid for Bills and must not be provided, use the DirectCost data type to push Expenses. + field: PaymentAllocations + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + validation: + information: + - details: Should be unique if WarnDuplicateBillNumber setting is On. + field: Reference + - details: Should not be longer than 21 characters. + field: Reference + warnings: [] + subTotal: + description: The total amount of the bill excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + totalAmount: + description: The amount of the bill, inclusive of tax + displayName: Total Amount + required: false + type: Number + required: true + type: Object + Sage 50 (UK): + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: The currency in which the bill is issued in. + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: This must match the supplier's default currency. + field: currency + dueDate: + description: Date when the bill is due. + displayName: Due Date + required: true + type: DateTime + issueDate: + description: Date when the bill was issued. + displayName: Date + required: true + type: DateTime + lineItems: + description: Line items of the bill. + displayName: Line Items + properties: + accountRef: + description: Identifier for the account. + displayName: Account Reference + properties: + id: + description: Identifier of the account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: accountRef.id + required: true + type: Object + description: + description: Description of the bill line item. + displayName: Description + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 60 characters. + field: lineItems.description + taxAmount: + description: Tax of the bill line item. + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Tax rate reference of a bill line item. + displayName: Tax Rate Reference + properties: + id: + description: ID of the tax rate. + displayName: Tax Rate Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: taxRateRef.id + required: true + type: Object + totalAmount: + description: The total amount of the bill line item, inclusive of the tax amount. + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: Tracking categories for the line item + displayName: Tracking Categories + properties: + id: + description: Prefixed identifier for tracking category e.g. project_{x}, department_{x}, costcode_{x} + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Cost codes assigned with costcode_{x} must exist in Sage50 and must be assigned in conjunction with a project + field: trackingCategoryRefs.id + - details: Projects assigned with project_{x} must exist in Sage50 and must be assigned in conjunction with a cost code + field: trackingCategoryRefs.id + - details: Departments assigned with department_{x} must exist in Sage50 + field: trackingCategoryRefs.id + required: false + type: Array + required: true + type: Array + note: + description: To be used for any additional information associated with the Bill line item. + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Maximum 60 characters + field: note + reference: + description: The reference to the bill. + displayName: Bill Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 30 characters. + field: reference + status: + description: The status of the bill + displayName: Status + options: + - displayName: Open + required: false + type: String + value: Open + required: false + type: String + validation: + information: + - details: If this is not set, it will default to 'Open'. + field: status + warnings: [] + supplierRef: + description: Supplier on the bill. + displayName: Supplier + properties: + id: + description: Identifier of the supplier. + displayName: Supplier Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier and have a max length of 8 characters. + field: supplierRef.id + required: true + type: Object + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + required: false + type: String + validation: + information: + - details: If supplied, must match the currency of the supplier. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Should not be longer than 2000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: If ItemRef is provided, then ID is required. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + note: + description: Note about the bill + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 2000 characters. + field: Note + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 25 characters. + field: Reference + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + required: true + type: Object + Sage Intacct: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + - displayName: Canadian Dollar + required: false + type: String + value: CAD + - displayName: Pound Sterling + required: false + type: String + value: GBP + - displayName: US Dollar + required: false + type: String + value: USD + - displayName: Rand + required: false + type: String + value: ZAR + required: false + type: String + validation: + information: [] + warnings: + - details: Must be provided if CurrencyRate is set. + field: Currency + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be greater than 0. + field: CurrencyRate + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: For item based line items, must be provided and must not be earlier than IssueDate. + field: DueDate + id: + description: The identifier for the bill, unique for the company + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Not supported for account based line items. Required for item based line items. A unique number for the bill will be appended to the value supplied, to ensure the ID is unique. + field: Id + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match to an existing Account Id. + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided for account based line items. Must not be provided for item based line items. + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: For account based line items, must be between 1 and 1000 characters. For item based line items, must be between 1 and 400 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match to an existing Item Id. + field: ItemRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided for item based line items. Must not be provided for account based line items. + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: For item based line items, must be provided and must not be negative. For account based line items, if provided must always be 0. + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be provided for account based line items. Must not be provided for item based line items. + field: LineItems.SubTotal + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match to an existing TaxRate Id. + field: TaxRateRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Is not supported for item based line items. + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must contain the type of the tracking category and the Id of the selected category, separated by a '-'. For example, 'DEPARTMENT-100'. + field: TrackingCategoryRefs.Id + - details: Custom tracking categories are only supported for account based line items. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: For item based line items, must be provided and must not be negative. For account based line items, if provided must always be 0. + field: LineItems.UnitAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Must either all be account based or all be item based. + field: LineItems + note: + description: Note about the bill + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Is not supported for item based line items. + field: Note + reference: + description: User friendly reference for the bill + displayName: Reference + required: true + type: String + validation: + information: [] + warnings: + - details: For account based line items, must be between 1 and 100 characters. For item based line items, must be between 1 and 45 characters. + field: Reference + status: + description: The current state of the bill + displayName: Bill Status + required: false + type: String + validation: + information: [] + warnings: + - details: Must be provided for item based line items. + field: Status + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match to an existing Supplier Id. + field: SupplierRef.Id + required: true + type: Object + required: true + type: Object + Sandbox: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + amountDue: + description: The amount outstanding on the bill + displayName: Amount Due + required: true + type: Number + currency: + description: Currency of the bill + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given bill currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + isDirectCost: + description: True if this bill is also mapped as a direct cost + displayName: Is Direct Cost + required: true + type: Boolean + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Payable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + customerRef: + description: Reference to the customer this line item is being tracked against + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + isBilledTo: + description: The type of item this line item is billed to. + displayName: Is Billed To + required: true + type: String + isRebilledTo: + description: The type of item this line item is billed to + displayName: Is Rebilled To + required: true + type: String + projectRef: + description: Reference to the project this line item is being tracked against + displayName: Project Reference + properties: + id: + description: The reference identifier for the Project + displayName: Identifier + required: true + type: String + name: + description: The name of the Project referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Note about the bill + displayName: Note + required: true + type: String + paymentAllocations: + description: A collection of payments allocated to the bill + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + purchaseOrderRefs: + description: List of References to the purchase order the bill was created from. + displayName: Purchase Order References + properties: + id: + description: Unique identifier for the purchase order in the accounting platform + displayName: Id + required: true + type: String + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: true + type: String + required: true + type: Array + reference: + description: User friendly reference for the bill + displayName: Reference + required: true + type: String + status: + description: The current state of the bill + displayName: Bill Status + required: true + type: String + subTotal: + description: The total amount of the bill excluding any taxes + displayName: Sub Total Amount + required: true + type: Number + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + supplierName: + description: The name of the supplier referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + taxAmount: + description: The total amount of tax on the bill + displayName: Tax Amount + required: true + type: Number + totalAmount: + description: The amount of the bill, inclusive of tax + displayName: Total Amount + required: true + type: Number + withholdingTax: + description: A collection of tax deductions + displayName: Withholding Tax + properties: + amount: + description: Deduction amount + displayName: Amount + required: true + type: Number + name: + description: Name of the deduction + displayName: Name + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If no rate is specified, the Xero day rate will be applied. + field: CurrencyRate + ref: https://central.xero.com/s/#CurrencySettings$Rates + warnings: [] + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided, if ItemRef is not provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided, if ItemRef is not provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must not be longer than 4000 characters long. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided, if AccountRef is not provided. + field: LineItems.ItemRef + warnings: [] + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot be mapped directly into Xero and will only be used for validation purposes. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: + - details: Must be provided if TaxAmount is provided. + field: TaxRateRef.Id + warnings: + - details: Must be a valid GUID. + field: TaxRateRef.Id + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must not be a parent tracking category. + field: TrackingCategoryRefs.Id + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + reference: + description: User friendly reference for the bill + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not exceed 255 charaters long. + field: Reference + warnings: [] + status: + description: The current state of the bill + displayName: Bill Status + options: + - displayName: Open + required: false + type: String + value: Open + - displayName: Draft + required: false + type: String + value: Draft + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: SupplierRef.Id + warnings: + - details: Must be a valid GUID. + field: SupplierRef.Id + - details: Must match the ID of an existing customer. + field: SupplierRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: SupplierRef + warnings: [] + required: true + type: Object + Zoho Books: + value: + description: A bill is an itemised record of goods purchased from or services provided by a supplier + displayName: Bill + properties: + currency: + description: Currency of the bill + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the supplier's currency + field: Currency + currencyRate: + description: The exchange rate between the currency of the bill and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be greater than or equal to 0 + field: CurrencyRate + dueDate: + description: The date the bill is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The date of the bill as recorded in the originating system. + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the bill + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if ItemRef is not set + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + discountAmount: + description: The value, in the given bill currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if AccountRef is not set + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: [] + warnings: + - details: The sum of subtotals over all the line items must be greater than or equal to 0 + field: LineItems + - details: Must not be empty + field: LineItems + note: + description: Note about the bill + displayName: Note + required: false + type: String + reference: + description: User friendly reference for the bill + displayName: Reference + required: true + type: String + status: + description: The current state of the bill + displayName: Bill Status + options: + - displayName: Open + required: false + type: String + value: Open + - displayName: Void + required: false + type: String + value: Void + required: true + type: String + supplierRef: + description: Reference to the supplier the bill has been received from + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update bill model + tags: + - Bills + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/chartOfAccounts": + get: + description: |- + Get create account model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=chartOfAccounts) for integrations that support creating an account. + operationId: get-create-chartOfAccounts-model + responses: + "200": + content: + application/json: + examples: + Exact (Netherlands): + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Asset.Assets.Cash + required: false + type: String + value: Asset.Assets.Cash + - displayName: Asset.Assets.Bank + required: false + type: String + value: Asset.Assets.Bank + - displayName: Asset.Assets.PaymentServices + required: false + type: String + value: Asset.Assets.PaymentServices + - displayName: Asset.Assets.AccountsReceivable + required: false + type: String + value: Asset.Assets.AccountsReceivable + - displayName: Liability.EquityAndLiabilities.AccountsPayable + required: false + type: String + value: Liability.EquityAndLiabilities.AccountsPayable + - displayName: Asset.Assets.VAT + required: false + type: String + value: Asset.Assets.VAT + - displayName: Liability.EquityAndLiabilities.EmployeesPayable + required: false + type: String + value: Liability.EquityAndLiabilities.EmployeesPayable + - displayName: Asset.Assets.PrepaidExpenses + required: false + type: String + value: Asset.Assets.PrepaidExpenses + - displayName: Liability.EquityAndLiabilities.AccruedExpenses + required: false + type: String + value: Liability.EquityAndLiabilities.AccruedExpenses + - displayName: Liability.EquityAndLiabilities.IncomeTaxesPayable + required: false + type: String + value: Liability.EquityAndLiabilities.IncomeTaxesPayable + - displayName: Asset.Assets.FixedAssets + required: false + type: String + value: Asset.Assets.FixedAssets + - displayName: Asset.Assets.OtherAssets + required: false + type: String + value: Asset.Assets.OtherAssets + - displayName: Asset.Assets.AccumulatedDeprecation + required: false + type: String + value: Asset.Assets.AccumulatedDeprecation + - displayName: Asset.Assets.Inventory + required: false + type: String + value: Asset.Assets.Inventory + - displayName: Equity.EquityAndLiabilities.CapitalStock + required: false + type: String + value: Equity.EquityAndLiabilities.CapitalStock + - displayName: Equity.EquityAndLiabilities.RetainedEarnings + required: false + type: String + value: Equity.EquityAndLiabilities.RetainedEarnings + - displayName: Liability.EquityAndLiabilities.LongTermDebt + required: false + type: String + value: Liability.EquityAndLiabilities.LongTermDebt + - displayName: Liability.EquityAndLiabilities.CurrentPortionOfDebt + required: false + type: String + value: Liability.EquityAndLiabilities.CurrentPortionOfDebt + - displayName: Unknown.EquityAndLiabilities.Intercompany + required: false + type: String + value: Unknown.EquityAndLiabilities.Intercompany + - displayName: Unknown.General.General + required: false + type: String + value: Unknown.General.General + - displayName: Income.NetIncome.Revenue + required: false + type: String + value: Income.NetIncome.Revenue + - displayName: Expense.NetIncome.CostOfGoods + required: false + type: String + value: Expense.NetIncome.CostOfGoods + - displayName: Expense.NetIncome.OtherCosts + required: false + type: String + value: Expense.NetIncome.OtherCosts + - displayName: Expense.NetIncome.SalesGeneralAdministrativeExpenses + required: false + type: String + value: Expense.NetIncome.SalesGeneralAdministrativeExpenses + - displayName: Expense.NetIncome.DeprecationCosts + required: false + type: String + value: Expense.NetIncome.DeprecationCosts + - displayName: Expense.NetIncome.ResearchAndDevelopment + required: false + type: String + value: Expense.NetIncome.ResearchAndDevelopment + - displayName: Expense.NetIncome.EmployeeCosts + required: false + type: String + value: Expense.NetIncome.EmployeeCosts + - displayName: Expense.NetIncome.EmploymentCosts + required: false + type: String + value: Expense.NetIncome.EmploymentCosts + - displayName: Expense.ExceptionalIncome.ExceptionalCosts + required: false + type: String + value: Expense.ExceptionalIncome.ExceptionalCosts + - displayName: Income.ExceptionalIncome.ExceptionalIncome + required: false + type: String + value: Income.ExceptionalIncome.ExceptionalIncome + - displayName: Expense.ExceptionalIncome.IncomeTaxes + required: false + type: String + value: Expense.ExceptionalIncome.IncomeTaxes + - displayName: Income.ExceptionalIncome.InterestIncome + required: false + type: String + value: Income.ExceptionalIncome.InterestIncome + required: true + type: String + validation: + information: + - details: Must be provided. + field: FullyQualifiedCategory + warnings: [] + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: + - details: Must be provided. + field: Name + warnings: [] + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: + - details: Must be provided. + field: NominalCode + warnings: [] + status: + description: The status of the account + displayName: Account Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Pending + required: false + type: String + value: Pending + - displayName: Unknown + required: false + type: String + value: Unknown + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + required: true + type: Object + Exact (UK): + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Asset.Assets.Cash + required: false + type: String + value: Asset.Assets.Cash + - displayName: Asset.Assets.Bank + required: false + type: String + value: Asset.Assets.Bank + - displayName: Asset.Assets.PaymentServices + required: false + type: String + value: Asset.Assets.PaymentServices + - displayName: Asset.Assets.AccountsReceivable + required: false + type: String + value: Asset.Assets.AccountsReceivable + - displayName: Liability.EquityAndLiabilities.AccountsPayable + required: false + type: String + value: Liability.EquityAndLiabilities.AccountsPayable + - displayName: Asset.Assets.VAT + required: false + type: String + value: Asset.Assets.VAT + - displayName: Liability.EquityAndLiabilities.EmployeesPayable + required: false + type: String + value: Liability.EquityAndLiabilities.EmployeesPayable + - displayName: Asset.Assets.PrepaidExpenses + required: false + type: String + value: Asset.Assets.PrepaidExpenses + - displayName: Liability.EquityAndLiabilities.AccruedExpenses + required: false + type: String + value: Liability.EquityAndLiabilities.AccruedExpenses + - displayName: Liability.EquityAndLiabilities.IncomeTaxesPayable + required: false + type: String + value: Liability.EquityAndLiabilities.IncomeTaxesPayable + - displayName: Asset.Assets.FixedAssets + required: false + type: String + value: Asset.Assets.FixedAssets + - displayName: Asset.Assets.OtherAssets + required: false + type: String + value: Asset.Assets.OtherAssets + - displayName: Asset.Assets.AccumulatedDeprecation + required: false + type: String + value: Asset.Assets.AccumulatedDeprecation + - displayName: Asset.Assets.Inventory + required: false + type: String + value: Asset.Assets.Inventory + - displayName: Equity.EquityAndLiabilities.CapitalStock + required: false + type: String + value: Equity.EquityAndLiabilities.CapitalStock + - displayName: Equity.EquityAndLiabilities.RetainedEarnings + required: false + type: String + value: Equity.EquityAndLiabilities.RetainedEarnings + - displayName: Liability.EquityAndLiabilities.LongTermDebt + required: false + type: String + value: Liability.EquityAndLiabilities.LongTermDebt + - displayName: Liability.EquityAndLiabilities.CurrentPortionOfDebt + required: false + type: String + value: Liability.EquityAndLiabilities.CurrentPortionOfDebt + - displayName: Unknown.EquityAndLiabilities.Intercompany + required: false + type: String + value: Unknown.EquityAndLiabilities.Intercompany + - displayName: Unknown.General.General + required: false + type: String + value: Unknown.General.General + - displayName: Income.NetIncome.Revenue + required: false + type: String + value: Income.NetIncome.Revenue + - displayName: Expense.NetIncome.CostOfGoods + required: false + type: String + value: Expense.NetIncome.CostOfGoods + - displayName: Expense.NetIncome.OtherCosts + required: false + type: String + value: Expense.NetIncome.OtherCosts + - displayName: Expense.NetIncome.SalesGeneralAdministrativeExpenses + required: false + type: String + value: Expense.NetIncome.SalesGeneralAdministrativeExpenses + - displayName: Expense.NetIncome.DeprecationCosts + required: false + type: String + value: Expense.NetIncome.DeprecationCosts + - displayName: Expense.NetIncome.ResearchAndDevelopment + required: false + type: String + value: Expense.NetIncome.ResearchAndDevelopment + - displayName: Expense.NetIncome.EmployeeCosts + required: false + type: String + value: Expense.NetIncome.EmployeeCosts + - displayName: Expense.NetIncome.EmploymentCosts + required: false + type: String + value: Expense.NetIncome.EmploymentCosts + - displayName: Expense.ExceptionalIncome.ExceptionalCosts + required: false + type: String + value: Expense.ExceptionalIncome.ExceptionalCosts + - displayName: Income.ExceptionalIncome.ExceptionalIncome + required: false + type: String + value: Income.ExceptionalIncome.ExceptionalIncome + - displayName: Expense.ExceptionalIncome.IncomeTaxes + required: false + type: String + value: Expense.ExceptionalIncome.IncomeTaxes + - displayName: Income.ExceptionalIncome.InterestIncome + required: false + type: String + value: Income.ExceptionalIncome.InterestIncome + required: true + type: String + validation: + information: + - details: Must be provided. + field: FullyQualifiedCategory + warnings: [] + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: + - details: Must be provided. + field: Name + warnings: [] + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: + - details: Must be provided. + field: NominalCode + warnings: [] + status: + description: The status of the account + displayName: Account Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Pending + required: false + type: String + value: Pending + - displayName: Unknown + required: false + type: String + value: Unknown + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + description: + description: Description of the account + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Description + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Bank + required: false + type: String + value: Asset.Bank + - displayName: Accounts Receivable + required: false + type: String + value: Asset.AccountReceivable + - displayName: Other Current Asset + required: false + type: String + value: Asset.OtherCurrentAsset + - displayName: Fixed Asset + required: false + type: String + value: Asset.FixedAsset + - displayName: Other Asset + required: false + type: String + value: Asset.OtherAsset + - displayName: Cash + required: false + type: String + value: Asset.CashAndBank + - displayName: Equipment Machinery + required: false + type: String + value: Asset.Property Plant and Equipment + - displayName: Credit Card + required: false + type: String + value: Liability.CreditCard + - displayName: Accounts Payable + required: false + type: String + value: Liability.AccountsPayable + - displayName: Other Current Liability + required: false + type: String + value: Liability.OtherCurrentLiability + - displayName: Long Term Liability + required: false + type: String + value: Liability.LongTermLiability + - displayName: Other Liability + required: false + type: String + value: Liability.OtherLiability + - displayName: Equity + required: false + type: String + value: Equity + - displayName: Retained Earnings + required: false + type: String + value: Equity.Equity + - displayName: Retained Earnings + required: false + type: String + value: Equity.Equity.RetainedEarnings + - displayName: Retained Earnings + required: false + type: String + value: Equity.Owner's Equity + - displayName: Income + required: false + type: String + value: Income + - displayName: Other Income + required: false + type: String + value: OtherIncome + - displayName: Expense + required: false + type: String + value: Expense + - displayName: Sales Marketing + required: false + type: String + value: Expense.Expense + - displayName: General Administrative + required: false + type: String + value: Expense.Expense.Insurance + - displayName: General Administrative + required: false + type: String + value: Expense.Overhead + - displayName: Repairs Maintenance + required: false + type: String + value: Expense.Expense.RepairMaintenance + - displayName: Other Expense + required: false + type: String + value: OtherExpense + - displayName: Cost of Sales + required: false + type: String + value: CostOfSales + - displayName: Other + required: false + type: String + value: Cost Of Goods Sold.Cost of Sales + required: true + type: String + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 60 characters + field: Name + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: [] + warnings: + - details: If alphanumeric is supported, must be between 1 and 10 characters. Otherwise format is x-xxxx + field: NominalCode + status: + description: The status of the account + displayName: Account Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + currency: + description: The currency of the account + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the base currency of the QuickBooks Desktop company + field: Currency + warnings: + - details: The currency must match the base currency of the QuickBooks Desktop company unless the FullyQualifiedCategory is 'Asset.AccountsReceivable','Liability.AccountsPayable' or 'Liability.CreditCard' + field: Currency + - details: Must be a three letter ISO code that matches an existing active currency in the QuickBooks Desktop company + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currentBalance: + description: The current balance in the account + displayName: Current Balance + required: false + type: Number + description: + description: Description of the account + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 200 characters. + field: Description + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Account Receivable + required: false + type: String + value: Asset.AccountsReceivable + - displayName: Fixed Asset + required: false + type: String + value: Asset.FixedAsset + - displayName: Other Current Asset + required: false + type: String + value: Asset.OtherCurrentAsset + - displayName: Other Asset + required: false + type: String + value: Asset.OtherAsset + - displayName: Income + required: false + type: String + value: Income.Income + - displayName: Other Income + required: false + type: String + value: Income.OtherIncome + - displayName: Accounts Payable + required: false + type: String + value: Liability.AccountsPayable + - displayName: Credit Card + required: false + type: String + value: Liability.CreditCard + - displayName: Long Term Liability + required: false + type: String + value: Liability.LongTermLiability + - displayName: Other Current Liability + required: false + type: String + value: Liability.OtherCurrentLiability + - displayName: Cost Of Goods Sold + required: false + type: String + value: Liability.CostOfGoodsSold + - displayName: Equity + required: false + type: String + value: Equity.Equity + - displayName: Expense + required: false + type: String + value: Expense.Expense + - displayName: Other Expense + required: false + type: String + value: Expense.OtherExpense + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Name + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 7 characters. + field: NominalCode + required: true + type: Object + QuickBooks Online: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + currency: + description: The currency of the account + displayName: Currency + required: false + type: String + validation: + information: + - details: When not specified company base currency will be used + field: Currency + warnings: [] + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Cash On Hand + required: false + type: String + value: Asset.Bank.CashOnHand + - displayName: Checking + required: false + type: String + value: Asset.Bank.Checking + - displayName: Money Market + required: false + type: String + value: Asset.Bank.MoneyMarket + - displayName: Rents Held In Trust + required: false + type: String + value: Asset.Bank.RentsHeldInTrust + - displayName: Savings + required: false + type: String + value: Asset.Bank.Savings + - displayName: Trust Accounts + required: false + type: String + value: Asset.Bank.TrustAccounts + - displayName: Cash And Cash Equivalents + required: false + type: String + value: Asset.Bank.CashAndCashEquivalents + - displayName: Other Earmarked Bank Accounts + required: false + type: String + value: Asset.Bank.OtherEarmarkedBankAccounts + - displayName: Allowance For Bad Debts + required: false + type: String + value: Asset.Other Current Asset.AllowanceForBadDebts + - displayName: Development Costs + required: false + type: String + value: Asset.Other Current Asset.DevelopmentCosts + - displayName: Employee Cash Advances + required: false + type: String + value: Asset.Other Current Asset.EmployeeCashAdvances + - displayName: Other Current Assets + required: false + type: String + value: Asset.Other Current Asset.OtherCurrentAssets + - displayName: Inventory + required: false + type: String + value: Asset.Other Current Asset.Inventory + - displayName: Investment Mortgage Real Estate Loans + required: false + type: String + value: Asset.Other Current Asset.Investment_MortgageRealEstateLoans + - displayName: Investment Other + required: false + type: String + value: Asset.Other Current Asset.Investment_Other + - displayName: Investment Tax Exempt Securities + required: false + type: String + value: Asset.Other Current Asset.Investment_TaxExemptSecurities + - displayName: Investment US Government Obligations + required: false + type: String + value: Asset.Other Current Asset.Investment_USGovernmentObligations + - displayName: Loans To Officers + required: false + type: String + value: Asset.Other Current Asset.LoansToOfficers + - displayName: Loans To Others + required: false + type: String + value: Asset.Other Current Asset.LoansToOthers + - displayName: Loans To Stockholders + required: false + type: String + value: Asset.Other Current Asset.LoansToStockholders + - displayName: Prepaid Expenses + required: false + type: String + value: Asset.Other Current Asset.PrepaidExpenses + - displayName: Retainage + required: false + type: String + value: Asset.Other Current Asset.Retainage + - displayName: Undeposited Funds + required: false + type: String + value: Asset.Other Current Asset.UndepositedFunds + - displayName: Assets Available For Sale + required: false + type: String + value: Asset.Other Current Asset.AssetsAvailableForSale + - displayName: Balance With Govt Authorities + required: false + type: String + value: Asset.Other Current Asset.BalWithGovtAuthorities + - displayName: Called Up Share Capital Not Paid + required: false + type: String + value: Asset.Other Current Asset.CalledUpShareCapitalNotPaid + - displayName: Expenditure Authorisations And Letters Of Credit + required: false + type: String + value: Asset.Other Current Asset.ExpenditureAuthorisationsAndLettersOfCredit + - displayName: Global Tax Deferred + required: false + type: String + value: Asset.Other Current Asset.GlobalTaxDeferred + - displayName: Global Tax Refund + required: false + type: String + value: Asset.Other Current Asset.GlobalTaxRefund + - displayName: Internal Transfers + required: false + type: String + value: Asset.Other Current Asset.InternalTransfers + - displayName: Other Consumables + required: false + type: String + value: Asset.Other Current Asset.OtherConsumables + - displayName: Provisions Current Assets + required: false + type: String + value: Asset.Other Current Asset.ProvisionsCurrentAssets + - displayName: Short Term Investments In Related Parties + required: false + type: String + value: Asset.Other Current Asset.ShortTermInvestmentsInRelatedParties + - displayName: Short Term Loans And Advances To Related Parties + required: false + type: String + value: Asset.Other Current Asset.ShortTermLoansAndAdvancesToRelatedParties + - displayName: Trade And Other Receivables + required: false + type: String + value: Asset.Other Current Asset.TradeAndOtherReceivables + - displayName: Accumulated Depletion + required: false + type: String + value: Asset.Fixed Asset.AccumulatedDepletion + - displayName: Accumulated Depreciation + required: false + type: String + value: Asset.Fixed Asset.AccumulatedDepreciation + - displayName: Depletable Assets + required: false + type: String + value: Asset.Fixed Asset.DepletableAssets + - displayName: Fixed Asset Computers + required: false + type: String + value: Asset.Fixed Asset.FixedAssetComputers + - displayName: Fixed Asset Copiers + required: false + type: String + value: Asset.Fixed Asset.FixedAssetCopiers + - displayName: Fixed Asset Furniture + required: false + type: String + value: Asset.Fixed Asset.FixedAssetFurniture + - displayName: Fixed Asset Phone + required: false + type: String + value: Asset.Fixed Asset.FixedAssetPhone + - displayName: Fixed Asset Photo Video + required: false + type: String + value: Asset.Fixed Asset.FixedAssetPhotoVideo + - displayName: Fixed Asset Software + required: false + type: String + value: Asset.Fixed Asset.FixedAssetSoftware + - displayName: Fixed Asset Other Tools Equipment + required: false + type: String + value: Asset.Fixed Asset.FixedAssetOtherToolsEquipment + - displayName: Furniture And Fixtures + required: false + type: String + value: Asset.Fixed Asset.FurnitureAndFixtures + - displayName: Land + required: false + type: String + value: Asset.Fixed Asset.Land + - displayName: Leasehold Improvements + required: false + type: String + value: Asset.Fixed Asset.LeaseholdImprovements + - displayName: Other Fixed Assets + required: false + type: String + value: Asset.Fixed Asset.OtherFixedAssets + - displayName: Accumulated Amortization + required: false + type: String + value: Asset.Fixed Asset.AccumulatedAmortization + - displayName: Buildings + required: false + type: String + value: Asset.Fixed Asset.Buildings + - displayName: Intangible Assets + required: false + type: String + value: Asset.Fixed Asset.IntangibleAssets + - displayName: Machinery And Equipment + required: false + type: String + value: Asset.Fixed Asset.MachineryAndEquipment + - displayName: Vehicles + required: false + type: String + value: Asset.Fixed Asset.Vehicles + - displayName: Assets In Course Of Construction + required: false + type: String + value: Asset.Fixed Asset.AssetsInCourseOfConstruction + - displayName: Capital Wip + required: false + type: String + value: Asset.Fixed Asset.CapitalWip + - displayName: Cumulative Depreciation On Intangible Assets + required: false + type: String + value: Asset.Fixed Asset.CumulativeDepreciationOnIntangibleAssets + - displayName: Intangible Assets Under Development + required: false + type: String + value: Asset.Fixed Asset.IntangibleAssetsUnderDevelopment + - displayName: Land Asset + required: false + type: String + value: Asset.Fixed Asset.LandAsset + - displayName: Non Current Assets + required: false + type: String + value: Asset.Fixed Asset.NonCurrentAssets + - displayName: Participating Interests + required: false + type: String + value: Asset.Fixed Asset.ParticipatingInterests + - displayName: Provisions Fixed Assets + required: false + type: String + value: Asset.Fixed Asset.ProvisionsFixedAssets + - displayName: Lease Buyout + required: false + type: String + value: Asset.Other Asset.LeaseBuyout + - displayName: Other Long Term Assets + required: false + type: String + value: Asset.Other Asset.OtherLongTermAssets + - displayName: Security Deposits + required: false + type: String + value: Asset.Other Asset.SecurityDeposits + - displayName: Accumulated Amortization Of Other Assets + required: false + type: String + value: Asset.Other Asset.AccumulatedAmortizationOfOtherAssets + - displayName: Goodwill + required: false + type: String + value: Asset.Other Asset.Goodwill + - displayName: Licenses + required: false + type: String + value: Asset.Other Asset.Licenses + - displayName: Organizational Costs + required: false + type: String + value: Asset.Other Asset.OrganizationalCosts + - displayName: Assets Held For Sale + required: false + type: String + value: Asset.Other Asset.AssetsHeldForSale + - displayName: Available For Sale Financial Assets + required: false + type: String + value: Asset.Other Asset.AvailableForSaleFinancialAssets + - displayName: Deferred Tax + required: false + type: String + value: Asset.Other Asset.DeferredTax + - displayName: Investments + required: false + type: String + value: Asset.Other Asset.Investments + - displayName: Long Term Investments + required: false + type: String + value: Asset.Other Asset.LongTermInvestments + - displayName: Long Term Loans And Advances To Related Parties + required: false + type: String + value: Asset.Other Asset.LongTermLoansAndAdvancesToRelatedParties + - displayName: Other Intangible Assets + required: false + type: String + value: Asset.Other Asset.OtherIntangibleAssets + - displayName: Other Long Term Investments + required: false + type: String + value: Asset.Other Asset.OtherLongTermInvestments + - displayName: Other Long Term Loans And Advances + required: false + type: String + value: Asset.Other Asset.OtherLongTermLoansAndAdvances + - displayName: Prepayments And Accrued Income + required: false + type: String + value: Asset.Other Asset.PrepaymentsAndAccruedIncome + - displayName: Provisions Non-Current Assets + required: false + type: String + value: Asset.Other Asset.ProvisionsNonCurrentAssets + - displayName: Accounts Receivable + required: false + type: String + value: Asset.Accounts Receivable.AccountsReceivable + - displayName: Advertising/Promotional + required: false + type: String + value: Expense.Expense.AdvertisingPromotional + - displayName: Bad Debts + required: false + type: String + value: Expense.Expense.BadDebts + - displayName: Bank Charges + required: false + type: String + value: Expense.Expense.BankCharges + - displayName: Charitable Contributions + required: false + type: String + value: Expense.Expense.CharitableContributions + - displayName: Commissions And Fees + required: false + type: String + value: Expense.Expense.CommissionsAndFees + - displayName: Entertainment + required: false + type: String + value: Expense.Expense.Entertainment + - displayName: Entertainment Meals + required: false + type: String + value: Expense.Expense.EntertainmentMeals + - displayName: Equipment Rental + required: false + type: String + value: Expense.Expense.EquipmentRental + - displayName: Finance Costs + required: false + type: String + value: Expense.Expense.FinanceCosts + - displayName: Global Tax Expense + required: false + type: String + value: Expense.Expense.GlobalTaxExpense + - displayName: Insurance + required: false + type: String + value: Expense.Expense.Insurance + - displayName: Interest Paid + required: false + type: String + value: Expense.Expense.InterestPaid + - displayName: Legal And Professional Fees + required: false + type: String + value: Expense.Expense.LegalProfessionalFees + - displayName: Office Expenses + required: false + type: String + value: Expense.Expense.OfficeExpenses + - displayName: Office/General Administrative Expenses + required: false + type: String + value: Expense.Expense.OfficeGeneralAdministrativeExpenses + - displayName: Other Business Expenses + required: false + type: String + value: Expense.Expense.OtherBusinessExpenses + - displayName: Other Miscellaneous Service Cost + required: false + type: String + value: Expense.Expense.OtherMiscellaneousServiceCost + - displayName: Promotional Meals + required: false + type: String + value: Expense.Expense.PromotionalMeals + - displayName: Rent Or Lease Of Buildings + required: false + type: String + value: Expense.Expense.RentOrLeaseOfBuildings + - displayName: Repair And Maintenance + required: false + type: String + value: Expense.Expense.RepairMaintenance + - displayName: Shipping, Freight And Delivery + required: false + type: String + value: Expense.Expense.ShippingFreightDelivery + - displayName: Supplies And Materials + required: false + type: String + value: Expense.Expense.SuppliesMaterials + - displayName: Travel + required: false + type: String + value: Expense.Expense.Travel + - displayName: Travel Meals + required: false + type: String + value: Expense.Expense.TravelMeals + - displayName: Utilities + required: false + type: String + value: Expense.Expense.Utilities + - displayName: Auto + required: false + type: String + value: Expense.Expense.Auto + - displayName: Cost Of Labor + required: false + type: String + value: Expense.Expense.CostOfLabor + - displayName: Dues And Subscriptions + required: false + type: String + value: Expense.Expense.DuesSubscriptions + - displayName: Payroll Expenses + required: false + type: String + value: Expense.Expense.PayrollExpenses + - displayName: Taxes Paid + required: false + type: String + value: Expense.Expense.TaxesPaid + - displayName: Unapplied Cash Bill Payment Expense + required: false + type: String + value: Expense.Expense.UnappliedCashBillPaymentExpense + - displayName: Utilities + required: false + type: String + value: Expense.Expense.Utilities + - displayName: Amortization Expense + required: false + type: String + value: Expense.Expense.AmortizationExpense + - displayName: Appropriations To Depreciation + required: false + type: String + value: Expense.Expense.AppropriationsToDepreciation + - displayName: Borrowing Cost + required: false + type: String + value: Expense.Expense.BorrowingCost + - displayName: Commissions And Fees + required: false + type: String + value: Expense.Expense.CommissionsAndFees + - displayName: Distribution Costs + required: false + type: String + value: Expense.Expense.DistributionCosts + - displayName: External Services + required: false + type: String + value: Expense.Expense.ExternalServices + - displayName: Extraordinary Charges + required: false + type: String + value: Expense.Expense.ExtraordinaryCharges + - displayName: Income Tax Expense + required: false + type: String + value: Expense.Expense.IncomeTaxExpense + - displayName: Loss On Discontinued Operations Net Of Tax + required: false + type: String + value: Expense.Expense.LossOnDiscontinuedOperationsNetOfTax + - displayName: Management Compensation + required: false + type: String + value: Expense.Expense.ManagementCompensation + - displayName: Other Current Operating Charges + required: false + type: String + value: Expense.Expense.OtherCurrentOperatingCharges + - displayName: Other External Services + required: false + type: String + value: Expense.Expense.OtherExternalServices + - displayName: Other Rental Costs + required: false + type: String + value: Expense.Expense.OtherRentalCosts + - displayName: Other Selling Expenses + required: false + type: String + value: Expense.Expense.OtherSellingExpenses + - displayName: Project Studies Surveys Assessments + required: false + type: String + value: Expense.Expense.ProjectStudiesSurveysAssessments + - displayName: Purchases Rebates + required: false + type: String + value: Expense.Expense.PurchasesRebates + - displayName: Shipping And Delivery Expense + required: false + type: String + value: Expense.Expense.ShippingAndDeliveryExpense + - displayName: Staff Costs + required: false + type: String + value: Expense.Expense.StaffCosts + - displayName: Sundry + required: false + type: String + value: Expense.Expense.Sundry + - displayName: Travel Expenses General And Admin Expenses + required: false + type: String + value: Expense.Expense.TravelExpensesGeneralAndAdminExpenses + - displayName: Travel Expenses Selling Expense + required: false + type: String + value: Expense.Expense.TravelExpensesSellingExpense + - displayName: Depreciation + required: false + type: String + value: Expense.Other Expense.Depreciation + - displayName: Exchange Gain Or Loss + required: false + type: String + value: Expense.Other Expense.ExchangeGainOrLoss + - displayName: Other Miscellaneous Expense + required: false + type: String + value: Expense.Other Expense.OtherMiscellaneousExpense + - displayName: Penalties And Settlements + required: false + type: String + value: Expense.Other Expense.PenaltiesSettlements + - displayName: Amortization + required: false + type: String + value: Expense.Other Expense.Amortization + - displayName: Gas And Fuel + required: false + type: String + value: Expense.Other Expense.GasAndFuel + - displayName: Home Office + required: false + type: String + value: Expense.Other Expense.HomeOffice + - displayName: Home Owner Rental Insurance + required: false + type: String + value: Expense.Other Expense.HomeOwnerRentalInsurance + - displayName: Other Home Office Expenses + required: false + type: String + value: Expense.Other Expense.OtherHomeOfficeExpenses + - displayName: Mortgage Interest + required: false + type: String + value: Expense.Other Expense.MortgageInterest + - displayName: Rent And Lease + required: false + type: String + value: Expense.Other Expense.RentAndLease + - displayName: Repairs And Maintenance + required: false + type: String + value: Expense.Other Expense.RepairsAndMaintenance + - displayName: Parking And Tolls + required: false + type: String + value: Expense.Other Expense.ParkingAndTolls + - displayName: Vehicle + required: false + type: String + value: Expense.Other Expense.Vehicle + - displayName: Vehicle Insurance + required: false + type: String + value: Expense.Other Expense.VehicleInsurance + - displayName: Vehicle Lease + required: false + type: String + value: Expense.Other Expense.VehicleLease + - displayName: Vehicle Loan Interest + required: false + type: String + value: Expense.Other Expense.VehicleLoanInterest + - displayName: Vehicle Loan + required: false + type: String + value: Expense.Other Expense.VehicleLoan + - displayName: Vehicle Registration + required: false + type: String + value: Expense.Other Expense.VehicleRegistration + - displayName: Vehicle Repairs + required: false + type: String + value: Expense.Other Expense.VehicleRepairs + - displayName: Other Vehicle Expenses + required: false + type: String + value: Expense.Other Expense.OtherVehicleExpenses + - displayName: Utilities + required: false + type: String + value: Expense.Other Expense.Utilities + - displayName: Wash And Road Services + required: false + type: String + value: Expense.Other Expense.WashAndRoadServices + - displayName: Deferred Tax Expense + required: false + type: String + value: Expense.Other Expense.DeferredTaxExpense + - displayName: Depletion + required: false + type: String + value: Expense.Other Expense.Depletion + - displayName: Exceptional Items + required: false + type: String + value: Expense.Other Expense.ExceptionalItems + - displayName: Extraordinary Items + required: false + type: String + value: Expense.Other Expense.ExtraordinaryItems + - displayName: Income Tax Other Expense + required: false + type: String + value: Expense.Other Expense.IncomeTaxOtherExpense + - displayName: Mat Credit + required: false + type: String + value: Expense.Other Expense.MatCredit + - displayName: Prior Period Items + required: false + type: String + value: Expense.Other Expense.PriorPeriodItems + - displayName: Tax Roundoff Gain Or Loss + required: false + type: String + value: Expense.Other Expense.TaxRoundoffGainOrLoss + - displayName: Equipment Rental - COS + required: false + type: String + value: Expense.Cost of Goods Sold.EquipmentRentalCos + - displayName: Other Costs Of Sales - COS + required: false + type: String + value: Expense.Cost of Goods Sold.OtherCostsOfServiceCos + - displayName: Shipping, Freight And Delivery - COS + required: false + type: String + value: Expense.Cost of Goods Sold.ShippingFreightDeliveryCos + - displayName: Supplies And Materials - COS + required: false + type: String + value: Expense.Cost of Goods Sold.SuppliesMaterialsCogs + - displayName: Cost Of Labor - COS + required: false + type: String + value: Expense.Cost of Goods Sold.CostOfLaborCos + - displayName: Cost Of Sales + required: false + type: String + value: Expense.Cost of Goods Sold.CostOfSales + - displayName: Freight And Delivery Cost + required: false + type: String + value: Expense.Cost of Goods Sold.FreightAndDeliveryCost + - displayName: Non Profit Income + required: false + type: String + value: Income.Income.NonProfitIncome + - displayName: Other Primary Income + required: false + type: String + value: Income.Income.OtherPrimaryIncome + - displayName: Sales Of ProductIncome + required: false + type: String + value: Income.Income.SalesOfProductIncome + - displayName: Service Fee Income + required: false + type: String + value: Income.Income.ServiceFeeIncome + - displayName: Discounts Refunds Given + required: false + type: String + value: Income.Income.DiscountsRefundsGiven + - displayName: Unapplied Cash Payment Income + required: false + type: String + value: Income.Income.UnappliedCashPaymentIncome + - displayName: Cash Receipt Income + required: false + type: String + value: Income.Income.CashReceiptIncome + - displayName: Operating Grants + required: false + type: String + value: Income.Income.OperatingGrants + - displayName: Other Current Operating Income + required: false + type: String + value: Income.Income.OtherCurrentOperatingIncome + - displayName: Own Work Capitalized + required: false + type: String + value: Income.Income.OwnWorkCapitalized + - displayName: Revenue General + required: false + type: String + value: Income.Income.RevenueGeneral + - displayName: Sales Retail + required: false + type: String + value: Income.Income.SalesRetail + - displayName: Sales Wholesale + required: false + type: String + value: Income.Income.SalesWholesale + - displayName: Savings By Tax Scheme + required: false + type: String + value: Income.Income.SavingsByTaxScheme + - displayName: Dividend Income + required: false + type: String + value: Income.Other Income.DividendIncome + - displayName: Interest Earned + required: false + type: String + value: Income.Other Income.InterestEarned + - displayName: Other Investment Income + required: false + type: String + value: Income.Other Income.OtherInvestmentIncome + - displayName: Other Miscellaneous Income + required: false + type: String + value: Income.Other Income.OtherMiscellaneousIncome + - displayName: Tax Exempt Interest + required: false + type: String + value: Income.Other Income.TaxExemptInterest + - displayName: Gain Loss On Sale Of Fixed Assets + required: false + type: String + value: Income.Other Income.GainLossOnSaleOfFixedAssets + - displayName: Gain Loss On Sale Of Investments + required: false + type: String + value: Income.Other Income.GainLossOnSaleOfInvestments + - displayName: Loss On Disposal Of Assets + required: false + type: String + value: Income.Other Income.LossOnDisposalOfAssets + - displayName: Other Operating Income + required: false + type: String + value: Income.Other Income.OtherOperatingIncome + - displayName: Unrealised Loss On Securities Net Of Tax + required: false + type: String + value: Income.Other Income.UnrealisedLossOnSecuritiesNetOfTax + - displayName: Accounts Payable + required: false + type: String + value: Liability.Accounts Payable.AccountsPayable + - displayName: Outstanding Dues Micro Small Enterprise + required: false + type: String + value: Liability.Accounts Payable.OutstandingDuesMicroSmallEnterprise + - displayName: Outstanding Dues Other Than Micro Small Enterprise + required: false + type: String + value: Liability.Accounts Payable.OutstandingDuesOtherThanMicroSmallEnterprise + - displayName: Credit Card + required: false + type: String + value: Liability.Credit Card.CreditCard + - displayName: Notes Payable + required: false + type: String + value: Liability.Long Term Liability.NotesPayable + - displayName: Other Long Term Liabilities + required: false + type: String + value: Liability.Long Term Liability.OtherLongTermLiabilities + - displayName: Shareholder Notes Payable + required: false + type: String + value: Liability.Long Term Liability.ShareholderNotesPayable + - displayName: Accruals And Deferred Income + required: false + type: String + value: Liability.Long Term Liability.AccrualsAndDeferredIncome + - displayName: Accrued Long Lerm Liabilities + required: false + type: String + value: Liability.Long Term Liability.AccruedLongLermLiabilities + - displayName: Accrued Vacation Payable + required: false + type: String + value: Liability.Long Term Liability.AccruedVacationPayable + - displayName: Bank Loans + required: false + type: String + value: Liability.Long Term Liability.BankLoans + - displayName: Debts Related To Participating Interests + required: false + type: String + value: Liability.Long Term Liability.DebtsRelatedToParticipatingInterests + - displayName: Deferred Tax Liabilities + required: false + type: String + value: Liability.Long Term Liability.DeferredTaxLiabilities + - displayName: Government And Other Public Authorities + required: false + type: String + value: Liability.Long Term Liability.GovernmentAndOtherPublicAuthorities + - displayName: Group And Associates + required: false + type: String + value: Liability.Long Term Liability.GroupAndAssociates + - displayName: Liabilities Related To Assets Held For Sale + required: false + type: String + value: Liability.Long Term Liability.LiabilitiesRelatedToAssetsHeldForSale + - displayName: Long Term Borrowings + required: false + type: String + value: Liability.Long Term Liability.LongTermBorrowings + - displayName: Long Term Debit + required: false + type: String + value: Liability.Long Term Liability.LongTermDebit + - displayName: Long Term Employee Benefit Obligations + required: false + type: String + value: Liability.Long Term Liability.LongTermEmployeeBenefitObligations + - displayName: Obligations Under Finance Leases + required: false + type: String + value: Liability.Long Term Liability.ObligationsUnderFinanceLeases + - displayName: Other Long Term Provisions + required: false + type: String + value: Liability.Long Term Liability.OtherLongTermProvisions + - displayName: Provision For Liabilities + required: false + type: String + value: Liability.Long Term Liability.ProvisionForLiabilities + - displayName: Provisions Non Current Liabilities + required: false + type: String + value: Liability.Long Term Liability.ProvisionsNonCurrentLiabilities + - displayName: Staff And Related Long Term Liability Accounts + required: false + type: String + value: Liability.Long Term Liability.StaffAndRelatedLongTermLiabilityAccounts + - displayName: Direct Deposit Payable + required: false + type: String + value: Liability.Other Current Liability.DirectDepositPayable + - displayName: Line Of Credit + required: false + type: String + value: Liability.Other Current Liability.LineOfCredit + - displayName: Loan Payable + required: false + type: String + value: Liability.Other Current Liability.LoanPayable + - displayName: Global Tax Payable + required: false + type: String + value: Liability.Other Current Liability.GlobalTaxPayable + - displayName: Global Tax Suspense + required: false + type: String + value: Liability.Other Current Liability.GlobalTaxSuspense + - displayName: Other Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.OtherCurrentLiabilities + - displayName: Payroll Clearing + required: false + type: String + value: Liability.Other Current Liability.PayrollClearing + - displayName: Payroll Tax Payable + required: false + type: String + value: Liability.Other Current Liability.PayrollTaxPayable + - displayName: Prepaid Expenses Payable + required: false + type: String + value: Liability.Other Current Liability.PrepaidExpensesPayable + - displayName: Rents In Trust Liability + required: false + type: String + value: Liability.Other Current Liability.RentsInTrustLiability + - displayName: Trust Accounts Liabilities + required: false + type: String + value: Liability.Other Current Liability.TrustAccountsLiabilities + - displayName: Federal Income Tax Payable + required: false + type: String + value: Liability.Other Current Liability.FederalIncomeTaxPayable + - displayName: Insurance Payable + required: false + type: String + value: Liability.Other Current Liability.InsurancePayable + - displayName: Sales Tax Payable + required: false + type: String + value: Liability.Other Current Liability.SalesTaxPayable + - displayName: State Local Income Tax Payable + required: false + type: String + value: Liability.Other Current Liability.StateLocalIncomeTaxPayable + - displayName: Accrued Liabilities + required: false + type: String + value: Liability.Other Current Liability.AccruedLiabilities + - displayName: Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.CurrentLiabilities + - displayName: Current Portion EmployeeBenefits Obligations + required: false + type: String + value: Liability.Other Current Liability.CurrentPortionEmployeeBenefitsObligations + - displayName: Current Portion Of Obligations Under Finance Leases + required: false + type: String + value: Liability.Other Current Liability.CurrentPortionOfObligationsUnderFinanceLeases + - displayName: Current Tax Liability + required: false + type: String + value: Liability.Other Current Liability.CurrentTaxLiability + - displayName: Dividends Payable + required: false + type: String + value: Liability.Other Current Liability.DividendsPayable + - displayName: Duties And Taxes + required: false + type: String + value: Liability.Other Current Liability.DutiesAndTaxes + - displayName: Interest Payables + required: false + type: String + value: Liability.Other Current Liability.InterestPayables + - displayName: Provision For Warranty Obligations + required: false + type: String + value: Liability.Other Current Liability.ProvisionForWarrantyObligations + - displayName: Provisions Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.ProvisionsCurrentLiabilities + - displayName: Short Term Borrowings + required: false + type: String + value: Liability.Other Current Liability.ShortTermBorrowings + - displayName: Social Security Agencies + required: false + type: String + value: Liability.Other Current Liability.SocialSecurityAgencies + - displayName: Staff And Related Liability Accounts + required: false + type: String + value: Liability.Other Current Liability.StaffAndRelatedLiabilityAccounts + - displayName: Sundry Debtors And Creditors + required: false + type: String + value: Liability.Other Current Liability.SundryDebtorsAndCreditors + - displayName: Trade And Other Payables + required: false + type: String + value: Liability.Other Current Liability.TradeAndOtherPayables + - displayName: Opening Balance Equity + required: false + type: String + value: Equity.Equity.OpeningBalanceEquity + - displayName: Partners Equity + required: false + type: String + value: Equity.Equity.PartnersEquity + - displayName: Retained Earnings + required: false + type: String + value: Equity.Equity.RetainedEarnings + - displayName: Accumulated Adjustment + required: false + type: String + value: Equity.Equity.AccumulatedAdjustment + - displayName: Owners Equity + required: false + type: String + value: Equity.Equity.OwnersEquity + - displayName: Paid In Capital Or Surplus + required: false + type: String + value: Equity.Equity.PaidInCapitalOrSurplus + - displayName: Partner Contributions + required: false + type: String + value: Equity.Equity.PartnerContributions + - displayName: Partner Distributions + required: false + type: String + value: Equity.Equity.PartnerDistributions + - displayName: Preferred Stock + required: false + type: String + value: Equity.Equity.PreferredStock + - displayName: Common Stock + required: false + type: String + value: Equity.Equity.CommonStock + - displayName: Treasury Stock + required: false + type: String + value: Equity.Equity.TreasuryStock + - displayName: Estimated Taxes + required: false + type: String + value: Equity.Equity.EstimatedTaxes + - displayName: Healthcare + required: false + type: String + value: Equity.Equity.Healthcare + - displayName: Personal Income + required: false + type: String + value: Equity.Equity.PersonalIncome + - displayName: Personal Expense + required: false + type: String + value: Equity.Equity.PersonalExpense + - displayName: Accumulated Other Comprehensive Income + required: false + type: String + value: Equity.Equity.AccumulatedOtherComprehensiveIncome + - displayName: Called Up Share Capital + required: false + type: String + value: Equity.Equity.CalledUpShareCapital + - displayName: Capital Reserves + required: false + type: String + value: Equity.Equity.CapitalReserves + - displayName: Dividend Disbursed + required: false + type: String + value: Equity.Equity.DividendDisbursed + - displayName: Equity In Earnings Of Subsiduaries + required: false + type: String + value: Equity.Equity.EquityInEarningsOfSubsiduaries + - displayName: Investment Grants + required: false + type: String + value: Equity.Equity.InvestmentGrants + - displayName: Money Received Against Share Warrants + required: false + type: String + value: Equity.Equity.MoneyReceivedAgainstShareWarrants + - displayName: Other Free Reserves + required: false + type: String + value: Equity.Equity.OtherFreeReserves + - displayName: Share Application Money Pending Allotment + required: false + type: String + value: Equity.Equity.ShareApplicationMoneyPendingAllotment + - displayName: Share Capital + required: false + type: String + value: Equity.Equity.ShareCapital + - displayName: Funds + required: false + type: String + value: Equity.Equity.Funds + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 100 characters + field: Name + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + validation: + information: + - details: If included must have a length between 1 and 7 characters + field: NominalCode + warnings: [] + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + currency: + description: The currency of the account + displayName: Currency + required: false + type: String + validation: + information: + - details: When not specified company base currency will be used + field: Currency + warnings: [] + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Cash On Hand + required: false + type: String + value: Asset.Bank.CashOnHand + - displayName: Checking + required: false + type: String + value: Asset.Bank.Checking + - displayName: Money Market + required: false + type: String + value: Asset.Bank.MoneyMarket + - displayName: Rents Held In Trust + required: false + type: String + value: Asset.Bank.RentsHeldInTrust + - displayName: Savings + required: false + type: String + value: Asset.Bank.Savings + - displayName: Trust Accounts + required: false + type: String + value: Asset.Bank.TrustAccounts + - displayName: Cash And Cash Equivalents + required: false + type: String + value: Asset.Bank.CashAndCashEquivalents + - displayName: Other Earmarked Bank Accounts + required: false + type: String + value: Asset.Bank.OtherEarmarkedBankAccounts + - displayName: Allowance For Bad Debts + required: false + type: String + value: Asset.Other Current Asset.AllowanceForBadDebts + - displayName: Development Costs + required: false + type: String + value: Asset.Other Current Asset.DevelopmentCosts + - displayName: Employee Cash Advances + required: false + type: String + value: Asset.Other Current Asset.EmployeeCashAdvances + - displayName: Other Current Assets + required: false + type: String + value: Asset.Other Current Asset.OtherCurrentAssets + - displayName: Inventory + required: false + type: String + value: Asset.Other Current Asset.Inventory + - displayName: Investment Mortgage Real Estate Loans + required: false + type: String + value: Asset.Other Current Asset.Investment_MortgageRealEstateLoans + - displayName: Investment Other + required: false + type: String + value: Asset.Other Current Asset.Investment_Other + - displayName: Investment Tax Exempt Securities + required: false + type: String + value: Asset.Other Current Asset.Investment_TaxExemptSecurities + - displayName: Investment US Government Obligations + required: false + type: String + value: Asset.Other Current Asset.Investment_USGovernmentObligations + - displayName: Loans To Officers + required: false + type: String + value: Asset.Other Current Asset.LoansToOfficers + - displayName: Loans To Others + required: false + type: String + value: Asset.Other Current Asset.LoansToOthers + - displayName: Loans To Stockholders + required: false + type: String + value: Asset.Other Current Asset.LoansToStockholders + - displayName: Prepaid Expenses + required: false + type: String + value: Asset.Other Current Asset.PrepaidExpenses + - displayName: Retainage + required: false + type: String + value: Asset.Other Current Asset.Retainage + - displayName: Undeposited Funds + required: false + type: String + value: Asset.Other Current Asset.UndepositedFunds + - displayName: Assets Available For Sale + required: false + type: String + value: Asset.Other Current Asset.AssetsAvailableForSale + - displayName: Balance With Govt Authorities + required: false + type: String + value: Asset.Other Current Asset.BalWithGovtAuthorities + - displayName: Called Up Share Capital Not Paid + required: false + type: String + value: Asset.Other Current Asset.CalledUpShareCapitalNotPaid + - displayName: Expenditure Authorisations And Letters Of Credit + required: false + type: String + value: Asset.Other Current Asset.ExpenditureAuthorisationsAndLettersOfCredit + - displayName: Global Tax Deferred + required: false + type: String + value: Asset.Other Current Asset.GlobalTaxDeferred + - displayName: Global Tax Refund + required: false + type: String + value: Asset.Other Current Asset.GlobalTaxRefund + - displayName: Internal Transfers + required: false + type: String + value: Asset.Other Current Asset.InternalTransfers + - displayName: Other Consumables + required: false + type: String + value: Asset.Other Current Asset.OtherConsumables + - displayName: Provisions Current Assets + required: false + type: String + value: Asset.Other Current Asset.ProvisionsCurrentAssets + - displayName: Short Term Investments In Related Parties + required: false + type: String + value: Asset.Other Current Asset.ShortTermInvestmentsInRelatedParties + - displayName: Short Term Loans And Advances To Related Parties + required: false + type: String + value: Asset.Other Current Asset.ShortTermLoansAndAdvancesToRelatedParties + - displayName: Trade And Other Receivables + required: false + type: String + value: Asset.Other Current Asset.TradeAndOtherReceivables + - displayName: Accumulated Depletion + required: false + type: String + value: Asset.Fixed Asset.AccumulatedDepletion + - displayName: Accumulated Depreciation + required: false + type: String + value: Asset.Fixed Asset.AccumulatedDepreciation + - displayName: Depletable Assets + required: false + type: String + value: Asset.Fixed Asset.DepletableAssets + - displayName: Fixed Asset Computers + required: false + type: String + value: Asset.Fixed Asset.FixedAssetComputers + - displayName: Fixed Asset Copiers + required: false + type: String + value: Asset.Fixed Asset.FixedAssetCopiers + - displayName: Fixed Asset Furniture + required: false + type: String + value: Asset.Fixed Asset.FixedAssetFurniture + - displayName: Fixed Asset Phone + required: false + type: String + value: Asset.Fixed Asset.FixedAssetPhone + - displayName: Fixed Asset Photo Video + required: false + type: String + value: Asset.Fixed Asset.FixedAssetPhotoVideo + - displayName: Fixed Asset Software + required: false + type: String + value: Asset.Fixed Asset.FixedAssetSoftware + - displayName: Fixed Asset Other Tools Equipment + required: false + type: String + value: Asset.Fixed Asset.FixedAssetOtherToolsEquipment + - displayName: Furniture And Fixtures + required: false + type: String + value: Asset.Fixed Asset.FurnitureAndFixtures + - displayName: Land + required: false + type: String + value: Asset.Fixed Asset.Land + - displayName: Leasehold Improvements + required: false + type: String + value: Asset.Fixed Asset.LeaseholdImprovements + - displayName: Other Fixed Assets + required: false + type: String + value: Asset.Fixed Asset.OtherFixedAssets + - displayName: Accumulated Amortization + required: false + type: String + value: Asset.Fixed Asset.AccumulatedAmortization + - displayName: Buildings + required: false + type: String + value: Asset.Fixed Asset.Buildings + - displayName: Intangible Assets + required: false + type: String + value: Asset.Fixed Asset.IntangibleAssets + - displayName: Machinery And Equipment + required: false + type: String + value: Asset.Fixed Asset.MachineryAndEquipment + - displayName: Vehicles + required: false + type: String + value: Asset.Fixed Asset.Vehicles + - displayName: Assets In Course Of Construction + required: false + type: String + value: Asset.Fixed Asset.AssetsInCourseOfConstruction + - displayName: Capital Wip + required: false + type: String + value: Asset.Fixed Asset.CapitalWip + - displayName: Cumulative Depreciation On Intangible Assets + required: false + type: String + value: Asset.Fixed Asset.CumulativeDepreciationOnIntangibleAssets + - displayName: Intangible Assets Under Development + required: false + type: String + value: Asset.Fixed Asset.IntangibleAssetsUnderDevelopment + - displayName: Land Asset + required: false + type: String + value: Asset.Fixed Asset.LandAsset + - displayName: Non Current Assets + required: false + type: String + value: Asset.Fixed Asset.NonCurrentAssets + - displayName: Participating Interests + required: false + type: String + value: Asset.Fixed Asset.ParticipatingInterests + - displayName: Provisions Fixed Assets + required: false + type: String + value: Asset.Fixed Asset.ProvisionsFixedAssets + - displayName: Lease Buyout + required: false + type: String + value: Asset.Other Asset.LeaseBuyout + - displayName: Other Long Term Assets + required: false + type: String + value: Asset.Other Asset.OtherLongTermAssets + - displayName: Security Deposits + required: false + type: String + value: Asset.Other Asset.SecurityDeposits + - displayName: Accumulated Amortization Of Other Assets + required: false + type: String + value: Asset.Other Asset.AccumulatedAmortizationOfOtherAssets + - displayName: Goodwill + required: false + type: String + value: Asset.Other Asset.Goodwill + - displayName: Licenses + required: false + type: String + value: Asset.Other Asset.Licenses + - displayName: Organizational Costs + required: false + type: String + value: Asset.Other Asset.OrganizationalCosts + - displayName: Assets Held For Sale + required: false + type: String + value: Asset.Other Asset.AssetsHeldForSale + - displayName: Available For Sale Financial Assets + required: false + type: String + value: Asset.Other Asset.AvailableForSaleFinancialAssets + - displayName: Deferred Tax + required: false + type: String + value: Asset.Other Asset.DeferredTax + - displayName: Investments + required: false + type: String + value: Asset.Other Asset.Investments + - displayName: Long Term Investments + required: false + type: String + value: Asset.Other Asset.LongTermInvestments + - displayName: Long Term Loans And Advances To Related Parties + required: false + type: String + value: Asset.Other Asset.LongTermLoansAndAdvancesToRelatedParties + - displayName: Other Intangible Assets + required: false + type: String + value: Asset.Other Asset.OtherIntangibleAssets + - displayName: Other Long Term Investments + required: false + type: String + value: Asset.Other Asset.OtherLongTermInvestments + - displayName: Other Long Term Loans And Advances + required: false + type: String + value: Asset.Other Asset.OtherLongTermLoansAndAdvances + - displayName: Prepayments And Accrued Income + required: false + type: String + value: Asset.Other Asset.PrepaymentsAndAccruedIncome + - displayName: Provisions Non-Current Assets + required: false + type: String + value: Asset.Other Asset.ProvisionsNonCurrentAssets + - displayName: Accounts Receivable + required: false + type: String + value: Asset.Accounts Receivable.AccountsReceivable + - displayName: Advertising/Promotional + required: false + type: String + value: Expense.Expense.AdvertisingPromotional + - displayName: Bad Debts + required: false + type: String + value: Expense.Expense.BadDebts + - displayName: Bank Charges + required: false + type: String + value: Expense.Expense.BankCharges + - displayName: Charitable Contributions + required: false + type: String + value: Expense.Expense.CharitableContributions + - displayName: Commissions And Fees + required: false + type: String + value: Expense.Expense.CommissionsAndFees + - displayName: Entertainment + required: false + type: String + value: Expense.Expense.Entertainment + - displayName: Entertainment Meals + required: false + type: String + value: Expense.Expense.EntertainmentMeals + - displayName: Equipment Rental + required: false + type: String + value: Expense.Expense.EquipmentRental + - displayName: Finance Costs + required: false + type: String + value: Expense.Expense.FinanceCosts + - displayName: Global Tax Expense + required: false + type: String + value: Expense.Expense.GlobalTaxExpense + - displayName: Insurance + required: false + type: String + value: Expense.Expense.Insurance + - displayName: Interest Paid + required: false + type: String + value: Expense.Expense.InterestPaid + - displayName: Legal And Professional Fees + required: false + type: String + value: Expense.Expense.LegalProfessionalFees + - displayName: Office Expenses + required: false + type: String + value: Expense.Expense.OfficeExpenses + - displayName: Office/General Administrative Expenses + required: false + type: String + value: Expense.Expense.OfficeGeneralAdministrativeExpenses + - displayName: Other Business Expenses + required: false + type: String + value: Expense.Expense.OtherBusinessExpenses + - displayName: Other Miscellaneous Service Cost + required: false + type: String + value: Expense.Expense.OtherMiscellaneousServiceCost + - displayName: Promotional Meals + required: false + type: String + value: Expense.Expense.PromotionalMeals + - displayName: Rent Or Lease Of Buildings + required: false + type: String + value: Expense.Expense.RentOrLeaseOfBuildings + - displayName: Repair And Maintenance + required: false + type: String + value: Expense.Expense.RepairMaintenance + - displayName: Shipping, Freight And Delivery + required: false + type: String + value: Expense.Expense.ShippingFreightDelivery + - displayName: Supplies And Materials + required: false + type: String + value: Expense.Expense.SuppliesMaterials + - displayName: Travel + required: false + type: String + value: Expense.Expense.Travel + - displayName: Travel Meals + required: false + type: String + value: Expense.Expense.TravelMeals + - displayName: Utilities + required: false + type: String + value: Expense.Expense.Utilities + - displayName: Auto + required: false + type: String + value: Expense.Expense.Auto + - displayName: Cost Of Labor + required: false + type: String + value: Expense.Expense.CostOfLabor + - displayName: Dues And Subscriptions + required: false + type: String + value: Expense.Expense.DuesSubscriptions + - displayName: Payroll Expenses + required: false + type: String + value: Expense.Expense.PayrollExpenses + - displayName: Taxes Paid + required: false + type: String + value: Expense.Expense.TaxesPaid + - displayName: Unapplied Cash Bill Payment Expense + required: false + type: String + value: Expense.Expense.UnappliedCashBillPaymentExpense + - displayName: Utilities + required: false + type: String + value: Expense.Expense.Utilities + - displayName: Amortization Expense + required: false + type: String + value: Expense.Expense.AmortizationExpense + - displayName: Appropriations To Depreciation + required: false + type: String + value: Expense.Expense.AppropriationsToDepreciation + - displayName: Borrowing Cost + required: false + type: String + value: Expense.Expense.BorrowingCost + - displayName: Commissions And Fees + required: false + type: String + value: Expense.Expense.CommissionsAndFees + - displayName: Distribution Costs + required: false + type: String + value: Expense.Expense.DistributionCosts + - displayName: External Services + required: false + type: String + value: Expense.Expense.ExternalServices + - displayName: Extraordinary Charges + required: false + type: String + value: Expense.Expense.ExtraordinaryCharges + - displayName: Income Tax Expense + required: false + type: String + value: Expense.Expense.IncomeTaxExpense + - displayName: Loss On Discontinued Operations Net Of Tax + required: false + type: String + value: Expense.Expense.LossOnDiscontinuedOperationsNetOfTax + - displayName: Management Compensation + required: false + type: String + value: Expense.Expense.ManagementCompensation + - displayName: Other Current Operating Charges + required: false + type: String + value: Expense.Expense.OtherCurrentOperatingCharges + - displayName: Other External Services + required: false + type: String + value: Expense.Expense.OtherExternalServices + - displayName: Other Rental Costs + required: false + type: String + value: Expense.Expense.OtherRentalCosts + - displayName: Other Selling Expenses + required: false + type: String + value: Expense.Expense.OtherSellingExpenses + - displayName: Project Studies Surveys Assessments + required: false + type: String + value: Expense.Expense.ProjectStudiesSurveysAssessments + - displayName: Purchases Rebates + required: false + type: String + value: Expense.Expense.PurchasesRebates + - displayName: Shipping And Delivery Expense + required: false + type: String + value: Expense.Expense.ShippingAndDeliveryExpense + - displayName: Staff Costs + required: false + type: String + value: Expense.Expense.StaffCosts + - displayName: Sundry + required: false + type: String + value: Expense.Expense.Sundry + - displayName: Travel Expenses General And Admin Expenses + required: false + type: String + value: Expense.Expense.TravelExpensesGeneralAndAdminExpenses + - displayName: Travel Expenses Selling Expense + required: false + type: String + value: Expense.Expense.TravelExpensesSellingExpense + - displayName: Depreciation + required: false + type: String + value: Expense.Other Expense.Depreciation + - displayName: Exchange Gain Or Loss + required: false + type: String + value: Expense.Other Expense.ExchangeGainOrLoss + - displayName: Other Miscellaneous Expense + required: false + type: String + value: Expense.Other Expense.OtherMiscellaneousExpense + - displayName: Penalties And Settlements + required: false + type: String + value: Expense.Other Expense.PenaltiesSettlements + - displayName: Amortization + required: false + type: String + value: Expense.Other Expense.Amortization + - displayName: Gas And Fuel + required: false + type: String + value: Expense.Other Expense.GasAndFuel + - displayName: Home Office + required: false + type: String + value: Expense.Other Expense.HomeOffice + - displayName: Home Owner Rental Insurance + required: false + type: String + value: Expense.Other Expense.HomeOwnerRentalInsurance + - displayName: Other Home Office Expenses + required: false + type: String + value: Expense.Other Expense.OtherHomeOfficeExpenses + - displayName: Mortgage Interest + required: false + type: String + value: Expense.Other Expense.MortgageInterest + - displayName: Rent And Lease + required: false + type: String + value: Expense.Other Expense.RentAndLease + - displayName: Repairs And Maintenance + required: false + type: String + value: Expense.Other Expense.RepairsAndMaintenance + - displayName: Parking And Tolls + required: false + type: String + value: Expense.Other Expense.ParkingAndTolls + - displayName: Vehicle + required: false + type: String + value: Expense.Other Expense.Vehicle + - displayName: Vehicle Insurance + required: false + type: String + value: Expense.Other Expense.VehicleInsurance + - displayName: Vehicle Lease + required: false + type: String + value: Expense.Other Expense.VehicleLease + - displayName: Vehicle Loan Interest + required: false + type: String + value: Expense.Other Expense.VehicleLoanInterest + - displayName: Vehicle Loan + required: false + type: String + value: Expense.Other Expense.VehicleLoan + - displayName: Vehicle Registration + required: false + type: String + value: Expense.Other Expense.VehicleRegistration + - displayName: Vehicle Repairs + required: false + type: String + value: Expense.Other Expense.VehicleRepairs + - displayName: Other Vehicle Expenses + required: false + type: String + value: Expense.Other Expense.OtherVehicleExpenses + - displayName: Utilities + required: false + type: String + value: Expense.Other Expense.Utilities + - displayName: Wash And Road Services + required: false + type: String + value: Expense.Other Expense.WashAndRoadServices + - displayName: Deferred Tax Expense + required: false + type: String + value: Expense.Other Expense.DeferredTaxExpense + - displayName: Depletion + required: false + type: String + value: Expense.Other Expense.Depletion + - displayName: Exceptional Items + required: false + type: String + value: Expense.Other Expense.ExceptionalItems + - displayName: Extraordinary Items + required: false + type: String + value: Expense.Other Expense.ExtraordinaryItems + - displayName: Income Tax Other Expense + required: false + type: String + value: Expense.Other Expense.IncomeTaxOtherExpense + - displayName: Mat Credit + required: false + type: String + value: Expense.Other Expense.MatCredit + - displayName: Prior Period Items + required: false + type: String + value: Expense.Other Expense.PriorPeriodItems + - displayName: Tax Roundoff Gain Or Loss + required: false + type: String + value: Expense.Other Expense.TaxRoundoffGainOrLoss + - displayName: Equipment Rental - COS + required: false + type: String + value: Expense.Cost of Goods Sold.EquipmentRentalCos + - displayName: Other Costs Of Sales - COS + required: false + type: String + value: Expense.Cost of Goods Sold.OtherCostsOfServiceCos + - displayName: Shipping, Freight And Delivery - COS + required: false + type: String + value: Expense.Cost of Goods Sold.ShippingFreightDeliveryCos + - displayName: Supplies And Materials - COS + required: false + type: String + value: Expense.Cost of Goods Sold.SuppliesMaterialsCogs + - displayName: Cost Of Labor - COS + required: false + type: String + value: Expense.Cost of Goods Sold.CostOfLaborCos + - displayName: Cost Of Sales + required: false + type: String + value: Expense.Cost of Goods Sold.CostOfSales + - displayName: Freight And Delivery Cost + required: false + type: String + value: Expense.Cost of Goods Sold.FreightAndDeliveryCost + - displayName: Non Profit Income + required: false + type: String + value: Income.Income.NonProfitIncome + - displayName: Other Primary Income + required: false + type: String + value: Income.Income.OtherPrimaryIncome + - displayName: Sales Of ProductIncome + required: false + type: String + value: Income.Income.SalesOfProductIncome + - displayName: Service Fee Income + required: false + type: String + value: Income.Income.ServiceFeeIncome + - displayName: Discounts Refunds Given + required: false + type: String + value: Income.Income.DiscountsRefundsGiven + - displayName: Unapplied Cash Payment Income + required: false + type: String + value: Income.Income.UnappliedCashPaymentIncome + - displayName: Cash Receipt Income + required: false + type: String + value: Income.Income.CashReceiptIncome + - displayName: Operating Grants + required: false + type: String + value: Income.Income.OperatingGrants + - displayName: Other Current Operating Income + required: false + type: String + value: Income.Income.OtherCurrentOperatingIncome + - displayName: Own Work Capitalized + required: false + type: String + value: Income.Income.OwnWorkCapitalized + - displayName: Revenue General + required: false + type: String + value: Income.Income.RevenueGeneral + - displayName: Sales Retail + required: false + type: String + value: Income.Income.SalesRetail + - displayName: Sales Wholesale + required: false + type: String + value: Income.Income.SalesWholesale + - displayName: Savings By Tax Scheme + required: false + type: String + value: Income.Income.SavingsByTaxScheme + - displayName: Dividend Income + required: false + type: String + value: Income.Other Income.DividendIncome + - displayName: Interest Earned + required: false + type: String + value: Income.Other Income.InterestEarned + - displayName: Other Investment Income + required: false + type: String + value: Income.Other Income.OtherInvestmentIncome + - displayName: Other Miscellaneous Income + required: false + type: String + value: Income.Other Income.OtherMiscellaneousIncome + - displayName: Tax Exempt Interest + required: false + type: String + value: Income.Other Income.TaxExemptInterest + - displayName: Gain Loss On Sale Of Fixed Assets + required: false + type: String + value: Income.Other Income.GainLossOnSaleOfFixedAssets + - displayName: Gain Loss On Sale Of Investments + required: false + type: String + value: Income.Other Income.GainLossOnSaleOfInvestments + - displayName: Loss On Disposal Of Assets + required: false + type: String + value: Income.Other Income.LossOnDisposalOfAssets + - displayName: Other Operating Income + required: false + type: String + value: Income.Other Income.OtherOperatingIncome + - displayName: Unrealised Loss On Securities Net Of Tax + required: false + type: String + value: Income.Other Income.UnrealisedLossOnSecuritiesNetOfTax + - displayName: Accounts Payable + required: false + type: String + value: Liability.Accounts Payable.AccountsPayable + - displayName: Outstanding Dues Micro Small Enterprise + required: false + type: String + value: Liability.Accounts Payable.OutstandingDuesMicroSmallEnterprise + - displayName: Outstanding Dues Other Than Micro Small Enterprise + required: false + type: String + value: Liability.Accounts Payable.OutstandingDuesOtherThanMicroSmallEnterprise + - displayName: Credit Card + required: false + type: String + value: Liability.Credit Card.CreditCard + - displayName: Notes Payable + required: false + type: String + value: Liability.Long Term Liability.NotesPayable + - displayName: Other Long Term Liabilities + required: false + type: String + value: Liability.Long Term Liability.OtherLongTermLiabilities + - displayName: Shareholder Notes Payable + required: false + type: String + value: Liability.Long Term Liability.ShareholderNotesPayable + - displayName: Accruals And Deferred Income + required: false + type: String + value: Liability.Long Term Liability.AccrualsAndDeferredIncome + - displayName: Accrued Long Lerm Liabilities + required: false + type: String + value: Liability.Long Term Liability.AccruedLongLermLiabilities + - displayName: Accrued Vacation Payable + required: false + type: String + value: Liability.Long Term Liability.AccruedVacationPayable + - displayName: Bank Loans + required: false + type: String + value: Liability.Long Term Liability.BankLoans + - displayName: Debts Related To Participating Interests + required: false + type: String + value: Liability.Long Term Liability.DebtsRelatedToParticipatingInterests + - displayName: Deferred Tax Liabilities + required: false + type: String + value: Liability.Long Term Liability.DeferredTaxLiabilities + - displayName: Government And Other Public Authorities + required: false + type: String + value: Liability.Long Term Liability.GovernmentAndOtherPublicAuthorities + - displayName: Group And Associates + required: false + type: String + value: Liability.Long Term Liability.GroupAndAssociates + - displayName: Liabilities Related To Assets Held For Sale + required: false + type: String + value: Liability.Long Term Liability.LiabilitiesRelatedToAssetsHeldForSale + - displayName: Long Term Borrowings + required: false + type: String + value: Liability.Long Term Liability.LongTermBorrowings + - displayName: Long Term Debit + required: false + type: String + value: Liability.Long Term Liability.LongTermDebit + - displayName: Long Term Employee Benefit Obligations + required: false + type: String + value: Liability.Long Term Liability.LongTermEmployeeBenefitObligations + - displayName: Obligations Under Finance Leases + required: false + type: String + value: Liability.Long Term Liability.ObligationsUnderFinanceLeases + - displayName: Other Long Term Provisions + required: false + type: String + value: Liability.Long Term Liability.OtherLongTermProvisions + - displayName: Provision For Liabilities + required: false + type: String + value: Liability.Long Term Liability.ProvisionForLiabilities + - displayName: Provisions Non Current Liabilities + required: false + type: String + value: Liability.Long Term Liability.ProvisionsNonCurrentLiabilities + - displayName: Staff And Related Long Term Liability Accounts + required: false + type: String + value: Liability.Long Term Liability.StaffAndRelatedLongTermLiabilityAccounts + - displayName: Direct Deposit Payable + required: false + type: String + value: Liability.Other Current Liability.DirectDepositPayable + - displayName: Line Of Credit + required: false + type: String + value: Liability.Other Current Liability.LineOfCredit + - displayName: Loan Payable + required: false + type: String + value: Liability.Other Current Liability.LoanPayable + - displayName: Global Tax Payable + required: false + type: String + value: Liability.Other Current Liability.GlobalTaxPayable + - displayName: Global Tax Suspense + required: false + type: String + value: Liability.Other Current Liability.GlobalTaxSuspense + - displayName: Other Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.OtherCurrentLiabilities + - displayName: Payroll Clearing + required: false + type: String + value: Liability.Other Current Liability.PayrollClearing + - displayName: Payroll Tax Payable + required: false + type: String + value: Liability.Other Current Liability.PayrollTaxPayable + - displayName: Prepaid Expenses Payable + required: false + type: String + value: Liability.Other Current Liability.PrepaidExpensesPayable + - displayName: Rents In Trust Liability + required: false + type: String + value: Liability.Other Current Liability.RentsInTrustLiability + - displayName: Trust Accounts Liabilities + required: false + type: String + value: Liability.Other Current Liability.TrustAccountsLiabilities + - displayName: Federal Income Tax Payable + required: false + type: String + value: Liability.Other Current Liability.FederalIncomeTaxPayable + - displayName: Insurance Payable + required: false + type: String + value: Liability.Other Current Liability.InsurancePayable + - displayName: Sales Tax Payable + required: false + type: String + value: Liability.Other Current Liability.SalesTaxPayable + - displayName: State Local Income Tax Payable + required: false + type: String + value: Liability.Other Current Liability.StateLocalIncomeTaxPayable + - displayName: Accrued Liabilities + required: false + type: String + value: Liability.Other Current Liability.AccruedLiabilities + - displayName: Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.CurrentLiabilities + - displayName: Current Portion EmployeeBenefits Obligations + required: false + type: String + value: Liability.Other Current Liability.CurrentPortionEmployeeBenefitsObligations + - displayName: Current Portion Of Obligations Under Finance Leases + required: false + type: String + value: Liability.Other Current Liability.CurrentPortionOfObligationsUnderFinanceLeases + - displayName: Current Tax Liability + required: false + type: String + value: Liability.Other Current Liability.CurrentTaxLiability + - displayName: Dividends Payable + required: false + type: String + value: Liability.Other Current Liability.DividendsPayable + - displayName: Duties And Taxes + required: false + type: String + value: Liability.Other Current Liability.DutiesAndTaxes + - displayName: Interest Payables + required: false + type: String + value: Liability.Other Current Liability.InterestPayables + - displayName: Provision For Warranty Obligations + required: false + type: String + value: Liability.Other Current Liability.ProvisionForWarrantyObligations + - displayName: Provisions Current Liabilities + required: false + type: String + value: Liability.Other Current Liability.ProvisionsCurrentLiabilities + - displayName: Short Term Borrowings + required: false + type: String + value: Liability.Other Current Liability.ShortTermBorrowings + - displayName: Social Security Agencies + required: false + type: String + value: Liability.Other Current Liability.SocialSecurityAgencies + - displayName: Staff And Related Liability Accounts + required: false + type: String + value: Liability.Other Current Liability.StaffAndRelatedLiabilityAccounts + - displayName: Sundry Debtors And Creditors + required: false + type: String + value: Liability.Other Current Liability.SundryDebtorsAndCreditors + - displayName: Trade And Other Payables + required: false + type: String + value: Liability.Other Current Liability.TradeAndOtherPayables + - displayName: Opening Balance Equity + required: false + type: String + value: Equity.Equity.OpeningBalanceEquity + - displayName: Partners Equity + required: false + type: String + value: Equity.Equity.PartnersEquity + - displayName: Retained Earnings + required: false + type: String + value: Equity.Equity.RetainedEarnings + - displayName: Accumulated Adjustment + required: false + type: String + value: Equity.Equity.AccumulatedAdjustment + - displayName: Owners Equity + required: false + type: String + value: Equity.Equity.OwnersEquity + - displayName: Paid In Capital Or Surplus + required: false + type: String + value: Equity.Equity.PaidInCapitalOrSurplus + - displayName: Partner Contributions + required: false + type: String + value: Equity.Equity.PartnerContributions + - displayName: Partner Distributions + required: false + type: String + value: Equity.Equity.PartnerDistributions + - displayName: Preferred Stock + required: false + type: String + value: Equity.Equity.PreferredStock + - displayName: Common Stock + required: false + type: String + value: Equity.Equity.CommonStock + - displayName: Treasury Stock + required: false + type: String + value: Equity.Equity.TreasuryStock + - displayName: Estimated Taxes + required: false + type: String + value: Equity.Equity.EstimatedTaxes + - displayName: Healthcare + required: false + type: String + value: Equity.Equity.Healthcare + - displayName: Personal Income + required: false + type: String + value: Equity.Equity.PersonalIncome + - displayName: Personal Expense + required: false + type: String + value: Equity.Equity.PersonalExpense + - displayName: Accumulated Other Comprehensive Income + required: false + type: String + value: Equity.Equity.AccumulatedOtherComprehensiveIncome + - displayName: Called Up Share Capital + required: false + type: String + value: Equity.Equity.CalledUpShareCapital + - displayName: Capital Reserves + required: false + type: String + value: Equity.Equity.CapitalReserves + - displayName: Dividend Disbursed + required: false + type: String + value: Equity.Equity.DividendDisbursed + - displayName: Equity In Earnings Of Subsiduaries + required: false + type: String + value: Equity.Equity.EquityInEarningsOfSubsiduaries + - displayName: Investment Grants + required: false + type: String + value: Equity.Equity.InvestmentGrants + - displayName: Money Received Against Share Warrants + required: false + type: String + value: Equity.Equity.MoneyReceivedAgainstShareWarrants + - displayName: Other Free Reserves + required: false + type: String + value: Equity.Equity.OtherFreeReserves + - displayName: Share Application Money Pending Allotment + required: false + type: String + value: Equity.Equity.ShareApplicationMoneyPendingAllotment + - displayName: Share Capital + required: false + type: String + value: Equity.Equity.ShareCapital + - displayName: Funds + required: false + type: String + value: Equity.Equity.Funds + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 100 characters + field: Name + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: false + type: String + validation: + information: + - details: If included must have a length between 1 and 7 characters + field: NominalCode + warnings: [] + required: true + type: Object + Sage Business Cloud Accounting: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + options: + - displayName: Sales + required: false + type: String + value: SALES + - displayName: Other Income + required: false + type: String + value: OTHER_INCOME + - displayName: Direct Expenses + required: false + type: String + value: DIRECT_EXPENSES + - displayName: Overheads + required: false + type: String + value: OVERHEADS + - displayName: Depreciation + required: false + type: String + value: DEPRECIATION + - displayName: Current Assets + required: false + type: String + value: CURRENT_ASSETS + - displayName: Fixed Assets + required: false + type: String + value: FIXED_ASSETS + - displayName: Future Assets + required: false + type: String + value: FUTURE_ASSETS + - displayName: Bank + required: false + type: String + value: BANK + - displayName: Current Liability + required: false + type: String + value: CURRENT_LIABILITY + - displayName: Future Liability + required: false + type: String + value: FUTURE_LIABILITY + - displayName: Equity + required: false + type: String + value: EQUITY + - displayName: Credit Card / Loan + required: false + type: String + value: LINE_OF_CREDIT + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + validation: + information: + - details: Should not be longer than 200 characters. + field: Name + warnings: [] + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: + - details: Should be a number between 1 and 99999999. + field: NominalCode + warnings: [] + required: true + type: Object + Sage Intacct: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + required: true + type: String + validation: + information: + - details: "Any category that is part of the hierarchy of one of: 'Assets', 'Equity', 'Liabilities', 'Total Expenses' and 'Total Income' is permitted." + field: FullyQualifiedCategory + warnings: [] + name: + description: Name of the account + displayName: Name + required: true + type: String + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + validation: + information: [] + warnings: + - details: Must be unique within the entity. + field: NominalCode + - details: Must be at most 24 characters in length, although restrictions may vary between entities. + field: NominalCode + status: + description: The status of the account + displayName: Account Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + type: + description: The type, or base category, of the account + displayName: Account Type + options: + - displayName: Asset + required: false + type: String + value: Asset + - displayName: Equity + required: false + type: String + value: Equity + - displayName: Expense + required: false + type: String + value: Expense + - displayName: Income + required: false + type: String + value: Income + - displayName: Liability + required: false + type: String + value: Liability + required: true + type: String + required: true + type: Object + Sandbox: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + currency: + description: The currency of the account + displayName: Currency + required: true + type: String + currentBalance: + description: The current balance in the account + displayName: Current Balance + required: true + type: Number + description: + description: Description of the account + displayName: Description + required: true + type: String + fullyQualifiedCategory: + description: The full category of the account e.g. Liability.Current or Income.Revenue + displayName: Fully Qualified Category + required: true + type: String + fullyQualifiedName: + description: The full name of the account e.g. Liability.Current.VAT or Income.Revenue.Sales + displayName: Fully Qualified Name + required: true + type: String + isBankAccount: + description: Confirms whether the nominal account represents a bank account or not + displayName: Is Bank Account? + required: true + type: Boolean + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + name: + description: Name of the account + displayName: Name + required: true + type: String + nominalCode: + description: The external reference given to each nominal account for a business + displayName: Nominal Code + required: true + type: String + status: + description: The status of the account + displayName: Account Status + required: true + type: String + type: + description: The type, or base category, of the account + displayName: Account Type + required: true + type: String + validDatatypeLinks: + description: Describes which fields on other data types are valid links to this account in the originating system + displayName: Valid Datatype Links + properties: + links: + description: A collection of absolute names of fields from other data types, e.g. Invoice.LineItems.AccountRef.Id + displayName: Links + required: true + type: Array + property: + description: The field on the source data type that other data types can link to + displayName: Property + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: Nominal Accounts are the categories a business uses to record transactions + displayName: Nominal Account + properties: + description: + description: Description for the nominal account. + displayName: Description + required: false + type: String + fullyQualifiedCategory: + description: Account type and category for nominal account. + displayName: Fully Qualified Category + options: + - displayName: Current Asset + required: false + type: String + value: Asset.Current + - displayName: Fixed Asset + required: false + type: String + value: Asset.Fixed + - displayName: Inventory + required: false + type: String + value: Asset.Inventory + - displayName: Non-current Asset + required: false + type: String + value: Asset.NonCurrent + - displayName: Prepayment + required: false + type: String + value: Asset.Prepayment + - displayName: Direct Costs + required: false + type: String + value: Expense.DirectCosts + - displayName: Expense + required: false + type: String + value: Expense.Expense + - displayName: Overhead + required: false + type: String + value: Expense.Overhead + - displayName: Superannuation + required: false + type: String + value: Expense.Superannuation + - displayName: Wages + required: false + type: String + value: Expense.Wages + - displayName: Sales + required: false + type: String + value: Income.Sales + - displayName: Revenue + required: false + type: String + value: Income.Revenue + - displayName: Other Income + required: false + type: String + value: Income.Other + - displayName: Current Liability + required: false + type: String + value: Liability.Current + - displayName: Depreciation + required: false + type: String + value: Liability.Depreciation + - displayName: Liability + required: false + type: String + value: Liability.Liability + - displayName: Non Current Liability + required: false + type: String + value: Liability.NonCurrent + - displayName: Pay As You Go Liability + required: false + type: String + value: Liability.PayAsYouGo + - displayName: Superannuation Liability + required: false + type: String + value: Liability.Superannuation + - displayName: Wages Payable Liability + required: false + type: String + value: Liability.WagesPayable + - displayName: Equity + required: false + type: String + value: Equity.Equity + required: true + type: String + name: + description: Name of account as it appears in the chart of accounts or general ledger. + displayName: Name + required: true + type: String + validation: + information: + - details: Payments are enabled to this account if the name ends in .PaymentsEnabled. + field: Name + warnings: [] + nominalCode: + description: Identifier for the nominal account. + displayName: Nominal Code + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 10 characters. + field: NominalCode + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create account model + tags: + - Accounts + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/creditNotes": + get: + description: |- + Get create/update credit note model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=creditNotes) for integrations that support creating and updating a credit note. + operationId: get-create-update-creditNotes-model + responses: + "200": + content: + application/json: + examples: + FreeAgent: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + options: + - displayName: AED + required: false + type: String + value: AED + - displayName: AMD + required: false + type: String + value: AMD + - displayName: AOA + required: false + type: String + value: AOA + - displayName: ARS + required: false + type: String + value: ARS + - displayName: AUD + required: false + type: String + value: AUD + - displayName: AWG + required: false + type: String + value: AWG + - displayName: AZN + required: false + type: String + value: AZN + - displayName: BBD + required: false + type: String + value: BBD + - displayName: BDT + required: false + type: String + value: BDT + - displayName: BGN + required: false + type: String + value: BGN + - displayName: BRL + required: false + type: String + value: BRL + - displayName: BWP + required: false + type: String + value: BWP + - displayName: CAD + required: false + type: String + value: CAD + - displayName: CHF + required: false + type: String + value: CHF + - displayName: CLP + required: false + type: String + value: CLP + - displayName: CNY + required: false + type: String + value: CNY + - displayName: COP + required: false + type: String + value: COP + - displayName: CRC + required: false + type: String + value: CRC + - displayName: CUC + required: false + type: String + value: CUC + - displayName: CUP + required: false + type: String + value: CUP + - displayName: CZK + required: false + type: String + value: CZK + - displayName: DKK + required: false + type: String + value: DKK + - displayName: DOP + required: false + type: String + value: DOP + - displayName: EGP + required: false + type: String + value: EGP + - displayName: EUR + required: false + type: String + value: EUR + - displayName: FJD + required: false + type: String + value: FJD + - displayName: GBP + required: false + type: String + value: GBP + - displayName: GEL + required: false + type: String + value: GEL + - displayName: GHS + required: false + type: String + value: GHS + - displayName: GTQ + required: false + type: String + value: GTQ + - displayName: GYD + required: false + type: String + value: GYD + - displayName: HKD + required: false + type: String + value: HKD + - displayName: HNL + required: false + type: String + value: HNL + - displayName: HRK + required: false + type: String + value: HRK + - displayName: HUF + required: false + type: String + value: HUF + - displayName: IDR + required: false + type: String + value: IDR + - displayName: ILS + required: false + type: String + value: ILS + - displayName: INR + required: false + type: String + value: INR + - displayName: ISK + required: false + type: String + value: ISK + - displayName: JMD + required: false + type: String + value: JMD + - displayName: JPY + required: false + type: String + value: JPY + - displayName: KES + required: false + type: String + value: KES + - displayName: KRW + required: false + type: String + value: KRW + - displayName: KWD + required: false + type: String + value: KWD + - displayName: KYD + required: false + type: String + value: KYD + - displayName: KZT + required: false + type: String + value: KZT + - displayName: LAK + required: false + type: String + value: LAK + - displayName: LBP + required: false + type: String + value: LBP + - displayName: LKR + required: false + type: String + value: LKR + - displayName: LTL + required: false + type: String + value: LTL + - displayName: LVL + required: false + type: String + value: LVL + - displayName: MAD + required: false + type: String + value: MAD + - displayName: MDL + required: false + type: String + value: MDL + - displayName: MGA + required: false + type: String + value: MGA + - displayName: MUR + required: false + type: String + value: MUR + - displayName: MVR + required: false + type: String + value: MVR + - displayName: MWK + required: false + type: String + value: MWK + - displayName: MXN + required: false + type: String + value: MXN + - displayName: MYR + required: false + type: String + value: MYR + - displayName: MZN + required: false + type: String + value: MZN + - displayName: NAD + required: false + type: String + value: NAD + - displayName: NGN + required: false + type: String + value: NGN + - displayName: NOK + required: false + type: String + value: NOK + - displayName: NPR + required: false + type: String + value: NPR + - displayName: NZD + required: false + type: String + value: NZD + - displayName: OMR + required: false + type: String + value: OMR + - displayName: PEN + required: false + type: String + value: PEN + - displayName: PHP + required: false + type: String + value: PHP + - displayName: PKR + required: false + type: String + value: PKR + - displayName: PLN + required: false + type: String + value: PLN + - displayName: QAR + required: false + type: String + value: QAR + - displayName: RON + required: false + type: String + value: RON + - displayName: RSD + required: false + type: String + value: RSD + - displayName: RUB + required: false + type: String + value: RUB + - displayName: RWF + required: false + type: String + value: RWF + - displayName: SAR + required: false + type: String + value: SAR + - displayName: SCR + required: false + type: String + value: SCR + - displayName: SEK + required: false + type: String + value: SEK + - displayName: SGD + required: false + type: String + value: SGD + - displayName: THB + required: false + type: String + value: THB + - displayName: TND + required: false + type: String + value: TND + - displayName: TRY + required: false + type: String + value: TRY + - displayName: TTD + required: false + type: String + value: TTD + - displayName: TWD + required: false + type: String + value: TWD + - displayName: TZS + required: false + type: String + value: TZS + - displayName: UAH + required: false + type: String + value: UAH + - displayName: UGX + required: false + type: String + value: UGX + - displayName: USD + required: false + type: String + value: USD + - displayName: UYU + required: false + type: String + value: UYU + - displayName: VEF + required: false + type: String + value: VEF + - displayName: VND + required: false + type: String + value: VND + - displayName: VUV + required: false + type: String + value: VUV + - displayName: XAF + required: false + type: String + value: XAF + - displayName: XCD + required: false + type: String + value: XCD + - displayName: XOF + required: false + type: String + value: XOF + - displayName: ZAR + required: false + type: String + value: ZAR + - displayName: ZMK + required: false + type: String + value: ZMK + required: false + type: String + validation: + information: + - details: If not specified, defaults to the company's native currency + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: + - details: If supplied, must be a positive number + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + subTotal: + description: The amount of the credit note, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the sum of all line items + field: TotalAmount + warnings: [] + required: true + type: Object + FreshBooks: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be valid Customer Id + field: CustomerRef.Id + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: false + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 13 characters + field: CreditNoteNumber + currency: + description: Currency of the credit note + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be greater than zero. + field: CurrencyRate + - details: Only valid if Currency is set + field: CurrencyRate + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + validation: + information: [] + warnings: + - details: Must not be supplied with an inventory item + field: LineItems.AccountRef + - details: Must be supplied except when an ItemRef is supplied + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + validation: + information: [] + warnings: + - details: Must have the same value for all line items + field: LineItems.TrackingCategoryRefs + - details: May contain a maximum of 1 item + field: LineItems.TrackingCategoryRefs + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater or equal to 0 + field: LineItems.UnitAmount + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 2000 characters + field: Note + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of TotalAmounts for the line items + field: TotalAmount + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + Oracle NetSuite: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be provided if and only if item does not have type 'Discount' + field: LineItems.SubTotal + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: false + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if item does not have type 'Discount' + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: A single location tracking category must be present on all LineItems. Optionally, a single class tracking category and a single department tracking category may be present on all LineItems too. + field: TrackingCategoryRefs.Id + warnings: [] + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.UnitAmount + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 11 characters. + field: CreditNoteNumber + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the customer + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the customer + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + required: true + type: Object + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: For US versions of QuickBooks Desktop this must be a Tax Code + field: TaxRateRef.Id + - details: For US versions of QuickBooks Desktop either 'Id' or 'Name' must be specified + field: TaxRateRef.Id + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: For US versions of QuickBooks Desktop with Sales Tax enabled this must be either 'Tax' or 'Non' + field: TaxRateRef.Name + - details: For US versions of QuickBooks Desktop either 'Id' or 'Name' must be specified + field: TaxRateRef.Name + required: false + type: Object + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: Note + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: false + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Maximum character length should not be longer than 4000. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then 'TAX' (Automated Sales Tax), 'NON' (no tax) or a custom tax rate can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: A tracking category of type CLASS can only be provided if ClassTrackingPerTxnLine is enabled for the QBO company. + field: TrackingCategoryRefs.Id + - details: Only one tracking category of type CLASS can be provided per item. + field: TrackingCategoryRefs.Id + - details: A tracking category of type DEPARTMENT should be declared at the top level item (first line item). + field: TrackingCategoryRefs.Id + - details: A tracking category of type DEPARTMENT can only be provided if TrackDepartments is enabled for the QBO company. + field: TrackingCategoryRefs.Id + - details: Only one tracking category of type DEPARTMENT can be provided per credit note. + field: TrackingCategoryRefs.Id + - details: Must match the ID of an existing tracking category and be of type DEPARTMENT or CLASS. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + note: + description: Note about the credit note + displayName: Note + required: false + type: String + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Tax will not be overridden if TotalTaxAmount is 0. + field: TotalTaxAmount + warnings: [] + required: true + type: Object + validation: + information: + - details: Automated Sales Tax is disabled for this company. + warnings: [] + Sage 50 (UK): + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: The reference number for this credit note + displayName: Credit Note Number + required: true + type: String + customerRef: + description: Customer to be pay. + displayName: Customer + properties: + id: + description: Identifier of the customer. + displayName: Customer Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer and have a max length of 8 characters. + field: customerRef.id + required: true + type: Object + lineItems: + description: Line items of the credit note. + displayName: Line Items + properties: + accountRef: + description: Identifier for the account. + displayName: Account Reference + properties: + id: + description: Identifier of the account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: accountRef.id + required: true + type: Object + taxRateRef: + description: Tax rate reference of a credit note line item. + displayName: Tax Rate Reference + properties: + id: + description: ID of the tax rate. + displayName: Tax Rate Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: taxRateRef.id + required: true + type: Object + trackingCategoryRefs: + description: Tracking categories for the line item + displayName: Tracking Categories + properties: + id: + description: Prefixed identifier for tracking category e.g. project_{x}, department_{x} + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Projects assigned with project_{x} must exist in Sage50 + field: trackingCategoryRefs.id + - details: Departments assigned with department_{x} must exist in Sage50 + field: trackingCategoryRefs.id + required: false + type: Array + required: true + type: Array + note: + description: To be used for any additional information associated with the credit note. + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Maximum 60 characters + field: note + status: + description: The status of the credit note + displayName: Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: false + type: String + validation: + information: + - details: If this is not set, it will default to 'Submitted'. + field: status + warnings: [] + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: + - details: If supplied, must match the currency of the customer. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Should not be longer than 2000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the total of the line including tax. + field: LineItems.TotalAmount + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + note: + description: Note about the credit note + displayName: Note + required: false + type: String + validation: + information: + - details: Should not be longer than 2000 characters. + field: Note + warnings: [] + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the sum of all line item total amounts. + field: TotalAmount + warnings: [] + required: true + type: Object + Sage Intacct: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + allocatedOnDate: + description: The date the credit note was allocated + displayName: Allocated On Date + required: false + type: DateTime + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: + - details: Must be provided if Sage Intacct is not configured to auto-generate an Adjustment Number, otherwise cannot be used. + field: CreditNoteNumber + warnings: [] + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: When supplying a currency ensure that it exists in your Sage Intacct entity otherwise the request will fail. + field: Currency + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be used to provide Customer Id. + field: CustomerRef.Id + warnings: [] + required: true + type: Object + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be used to provide the date the Credit Note was created. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be an existing GL Account in Sage Intacct and not linked to any bank account. + field: AccountRef.Id + warnings: [] + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: + - details: Must be an existing tax rate in Sage Intacct. + field: TaxRateRef.Id + warnings: [] + required: false + type: Object + validation: + information: + - details: It is only required for VAT enabled transactions. + field: LineItems.TaxRateRef + warnings: [] + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: false + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: false + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must be zero or greater. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must contain at least one line item. + field: LineItems + warnings: [] + note: + description: Note about the credit note + displayName: Note + required: false + type: String + status: + description: The current state of a credit note + displayName: Credit Note Status + required: true + type: String + validation: + information: + - details: Must be either Draft or Submitted. + field: Status + warnings: [] + required: true + type: Object + Sandbox: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + additionalTaxAmount: + description: Tax added to the total tax of the lines + displayName: Additional Tax Amount + required: true + type: Number + additionalTaxPercentage: + description: The percentage of the additional tax to the TotalAmount + displayName: Additional Tax Percentage + required: true + type: Number + allocatedOnDate: + description: The date the credit note was allocated + displayName: Allocated On Date + required: true + type: DateTime + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: true + type: String + currency: + description: Currency of the credit note + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services credited + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given credit note currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + isDirectIncome: + description: True if this invoice is also mapped as a direct income + displayName: Is Direct Income + required: true + type: Boolean + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Receivable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + customerRef: + description: Reference to the customer this line item is being tracked against + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + isBilledTo: + description: The type of item this line item is billed to. + displayName: Is Billed To + required: true + type: String + isRebilledTo: + description: The type of item this line item is billed to + displayName: Is Rebilled To + required: true + type: String + projectRef: + description: Reference to the project this line item is being tracked against + displayName: Project Reference + properties: + id: + description: The reference identifier for the Project + displayName: Identifier + required: true + type: String + name: + description: The name of the Project referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Note about the credit note + displayName: Note + required: true + type: String + paymentAllocations: + description: A collection of payments that are allocated to (i.e. spend) the credit note + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + remainingCredit: + description: Unused balance of total amount originally raised + displayName: Remaining Credit + required: true + type: Number + status: + description: The current state of a credit note + displayName: Credit Note Status + required: true + type: String + subTotal: + description: The amount of the credit note, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + totalDiscount: + description: The value, in the given credit note currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + totalTaxAmount: + description: The amount of tax for the credit note + displayName: Tax Amount + required: true + type: Number + withholdingTax: + description: A collection of tax deductions + displayName: Withholding Tax + properties: + amount: + description: Deduction amount + displayName: Amount + required: true + type: Number + name: + description: Name of the deduction + displayName: Name + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: A credit note can be thought of as a voucher issued to a customer. It can be applied against one or multiple invoices to reduce their balance. + displayName: Accounts Receivable Credit Note + properties: + creditNoteNumber: + description: User friendly reference for the credit note + displayName: Credit Note Number + required: false + type: String + validation: + information: + - details: Must not be longer than 225 characters long. + field: CreditNoteNumber + warnings: [] + currency: + description: Currency of the credit note + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the credit note and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the credit note has been issued to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must be a valid GUID. + field: CustomerRef.Id + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: CustomerRef + warnings: [] + issueDate: + description: The date the credit note was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the credit note + displayName: Line item + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services credited + displayName: Description + required: false + type: String + validation: + information: + - details: Must be provided when itemRef is not provided, or when the item has no sales description in Xero. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services credited + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: It will not be mapped directly into Xero as Xero computes it automatically on its end. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: It will not be mapped directly into Xero as Xero computes it automatically on its end. + field: LineItems.TotalAmount + trackingCategoryRefs: + description: A collection of categories ths item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + status: + description: The current state of a credit note + displayName: Credit Note Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + totalAmount: + description: The total amount of the credit note, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must equal the sum of the link items amount. + field: TotalAmount + warnings: + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update credit note model + tags: + - Credit notes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/customers": + get: + description: |- + Get create/update customer model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=customers) for integrations that support creating and updating customers. + operationId: get-create-update-customers-model + responses: + "200": + content: + application/json: + examples: + Exact (Netherlands): + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a 2-letter country code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only the first address provided will be considered, all other entries will be not be recorded + field: Addresses + warnings: [] + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + email: + description: The email address for the contact + displayName: Email + required: false + type: String + name: + description: The name of the contact + displayName: Name + required: true + type: String + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: false + type: String + required: false + type: Array + required: true + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Only for Exact Netherlands, if provided, must be exactly 20 characters in length + field: RegistrationNumber + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Exact (UK): + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a 2-letter country code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only the first address provided will be considered, all other entries will be not be recorded + field: Addresses + warnings: [] + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + email: + description: The email address for the contact + displayName: Email + required: false + type: String + name: + description: The name of the contact + displayName: Name + required: true + type: String + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: false + type: String + required: false + type: Array + required: true + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Only for Exact Netherlands, if provided, must be exactly 20 characters in length + field: RegistrationNumber + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + FreeAgent: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only one address may be specified + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: true + type: String + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + email: + description: The email address for the contact + displayName: Email + required: true + type: String + name: + description: The name of the contact + displayName: Name + options: + - displayName: Billing Email + required: false + type: String + value: Billing Email + required: true + type: String + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + required: true + type: Array + required: false + type: Array + validation: + information: + - details: Billing Email should be specified in a different contact entry with the specific corresponding name. + field: Contacts + warnings: [] + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + FreshBooks: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: [] + warnings: + - details: No more than two addresses can be added + field: Addresses + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: false + type: String + validation: + information: + - details: The part of the name preceding the first space will be assigned to first name, the remainder to last name + field: ContactName + warnings: [] + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + email: + description: The email address for the contact + displayName: Email + required: true + type: String + name: + description: The name of the contact + displayName: Name + required: true + type: String + validation: + information: + - details: The part of the name preceding the first space will be assigned to first name, the remainder to last name + field: Contacts.Name + warnings: [] + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + required: true + type: Array + validation: + information: [] + warnings: + - details: No more than two phone numbers per contact can be added + field: Contacts.Phone + required: false + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: false + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + options: + - displayName: AED + required: false + type: Array + value: AED + - displayName: AFN + required: false + type: Array + value: AFN + - displayName: ALL + required: false + type: Array + value: ALL + - displayName: AMD + required: false + type: Array + value: AMD + - displayName: ANG + required: false + type: Array + value: ANG + - displayName: AOA + required: false + type: Array + value: AOA + - displayName: ARS + required: false + type: Array + value: ARS + - displayName: AUD + required: false + type: Array + value: AUD + - displayName: AWG + required: false + type: Array + value: AWG + - displayName: AZN + required: false + type: Array + value: AZN + - displayName: BAM + required: false + type: Array + value: BAM + - displayName: BBD + required: false + type: Array + value: BBD + - displayName: BDT + required: false + type: Array + value: BDT + - displayName: BGN + required: false + type: Array + value: BGN + - displayName: BHD + required: false + type: Array + value: BHD + - displayName: BIF + required: false + type: Array + value: BIF + - displayName: BMD + required: false + type: Array + value: BMD + - displayName: BND + required: false + type: Array + value: BND + - displayName: BOB + required: false + type: Array + value: BOB + - displayName: BRL + required: false + type: Array + value: BRL + - displayName: BSD + required: false + type: Array + value: BSD + - displayName: BTN + required: false + type: Array + value: BTN + - displayName: BWP + required: false + type: Array + value: BWP + - displayName: BYR + required: false + type: Array + value: BYR + - displayName: BZD + required: false + type: Array + value: BZD + - displayName: CAD + required: false + type: Array + value: CAD + - displayName: CDF + required: false + type: Array + value: CDF + - displayName: CHF + required: false + type: Array + value: CHF + - displayName: CLP + required: false + type: Array + value: CLP + - displayName: CNY + required: false + type: Array + value: CNY + - displayName: COP + required: false + type: Array + value: COP + - displayName: CRC + required: false + type: Array + value: CRC + - displayName: CUC + required: false + type: Array + value: CUC + - displayName: CUP + required: false + type: Array + value: CUP + - displayName: CVE + required: false + type: Array + value: CVE + - displayName: CZK + required: false + type: Array + value: CZK + - displayName: DJF + required: false + type: Array + value: DJF + - displayName: DKK + required: false + type: Array + value: DKK + - displayName: DOP + required: false + type: Array + value: DOP + - displayName: DZD + required: false + type: Array + value: DZD + - displayName: EGP + required: false + type: Array + value: EGP + - displayName: ERN + required: false + type: Array + value: ERN + - displayName: ETB + required: false + type: Array + value: ETB + - displayName: EUR + required: false + type: Array + value: EUR + - displayName: FJD + required: false + type: Array + value: FJD + - displayName: FKP + required: false + type: Array + value: FKP + - displayName: GBP + required: false + type: Array + value: GBP + - displayName: GEL + required: false + type: Array + value: GEL + - displayName: GGP + required: false + type: Array + value: GGP + - displayName: GHS + required: false + type: Array + value: GHS + - displayName: GIP + required: false + type: Array + value: GIP + - displayName: GMD + required: false + type: Array + value: GMD + - displayName: GNF + required: false + type: Array + value: GNF + - displayName: GTQ + required: false + type: Array + value: GTQ + - displayName: GYD + required: false + type: Array + value: GYD + - displayName: HKD + required: false + type: Array + value: HKD + - displayName: HNL + required: false + type: Array + value: HNL + - displayName: HRK + required: false + type: Array + value: HRK + - displayName: HTG + required: false + type: Array + value: HTG + - displayName: HUF + required: false + type: Array + value: HUF + - displayName: IDR + required: false + type: Array + value: IDR + - displayName: ILS + required: false + type: Array + value: ILS + - displayName: IMP + required: false + type: Array + value: IMP + - displayName: INR + required: false + type: Array + value: INR + - displayName: IQD + required: false + type: Array + value: IQD + - displayName: IRR + required: false + type: Array + value: IRR + - displayName: ISK + required: false + type: Array + value: ISK + - displayName: JEP + required: false + type: Array + value: JEP + - displayName: JMD + required: false + type: Array + value: JMD + - displayName: JOD + required: false + type: Array + value: JOD + - displayName: JPY + required: false + type: Array + value: JPY + - displayName: KES + required: false + type: Array + value: KES + - displayName: KGS + required: false + type: Array + value: KGS + - displayName: KHR + required: false + type: Array + value: KHR + - displayName: KMF + required: false + type: Array + value: KMF + - displayName: KPW + required: false + type: Array + value: KPW + - displayName: KRW + required: false + type: Array + value: KRW + - displayName: KWD + required: false + type: Array + value: KWD + - displayName: KYD + required: false + type: Array + value: KYD + - displayName: KZT + required: false + type: Array + value: KZT + - displayName: LAK + required: false + type: Array + value: LAK + - displayName: LBP + required: false + type: Array + value: LBP + - displayName: LKR + required: false + type: Array + value: LKR + - displayName: LRD + required: false + type: Array + value: LRD + - displayName: LSL + required: false + type: Array + value: LSL + - displayName: LYD + required: false + type: Array + value: LYD + - displayName: MAD + required: false + type: Array + value: MAD + - displayName: MDL + required: false + type: Array + value: MDL + - displayName: MGA + required: false + type: Array + value: MGA + - displayName: MKD + required: false + type: Array + value: MKD + - displayName: MMK + required: false + type: Array + value: MMK + - displayName: MNT + required: false + type: Array + value: MNT + - displayName: MOP + required: false + type: Array + value: MOP + - displayName: MRO + required: false + type: Array + value: MRO + - displayName: MUR + required: false + type: Array + value: MUR + - displayName: MVR + required: false + type: Array + value: MVR + - displayName: MWK + required: false + type: Array + value: MWK + - displayName: MXN + required: false + type: Array + value: MXN + - displayName: MYR + required: false + type: Array + value: MYR + - displayName: MZN + required: false + type: Array + value: MZN + - displayName: NAD + required: false + type: Array + value: NAD + - displayName: NGN + required: false + type: Array + value: NGN + - displayName: NIO + required: false + type: Array + value: NIO + - displayName: NOK + required: false + type: Array + value: NOK + - displayName: NPR + required: false + type: Array + value: NPR + - displayName: NZD + required: false + type: Array + value: NZD + - displayName: OMR + required: false + type: Array + value: OMR + - displayName: PAB + required: false + type: Array + value: PAB + - displayName: PEN + required: false + type: Array + value: PEN + - displayName: PGK + required: false + type: Array + value: PGK + - displayName: PHP + required: false + type: Array + value: PHP + - displayName: PKR + required: false + type: Array + value: PKR + - displayName: PLN + required: false + type: Array + value: PLN + - displayName: PYG + required: false + type: Array + value: PYG + - displayName: QAR + required: false + type: Array + value: QAR + - displayName: RON + required: false + type: Array + value: RON + - displayName: RSD + required: false + type: Array + value: RSD + - displayName: RUB + required: false + type: Array + value: RUB + - displayName: RWF + required: false + type: Array + value: RWF + - displayName: SAR + required: false + type: Array + value: SAR + - displayName: SBD + required: false + type: Array + value: SBD + - displayName: SCR + required: false + type: Array + value: SCR + - displayName: SDG + required: false + type: Array + value: SDG + - displayName: SEK + required: false + type: Array + value: SEK + - displayName: SGD + required: false + type: Array + value: SGD + - displayName: SHP + required: false + type: Array + value: SHP + - displayName: SLL + required: false + type: Array + value: SLL + - displayName: SOS + required: false + type: Array + value: SOS + - displayName: SPL + required: false + type: Array + value: SPL + - displayName: SRD + required: false + type: Array + value: SRD + - displayName: STD + required: false + type: Array + value: STD + - displayName: SVC + required: false + type: Array + value: SVC + - displayName: SYP + required: false + type: Array + value: SYP + - displayName: SZL + required: false + type: Array + value: SZL + - displayName: THB + required: false + type: Array + value: THB + - displayName: TJS + required: false + type: Array + value: TJS + - displayName: TMT + required: false + type: Array + value: TMT + - displayName: TND + required: false + type: Array + value: TND + - displayName: TOP + required: false + type: Array + value: TOP + - displayName: TRY + required: false + type: Array + value: TRY + - displayName: TTD + required: false + type: Array + value: TTD + - displayName: TVD + required: false + type: Array + value: TVD + - displayName: TWD + required: false + type: Array + value: TWD + - displayName: TZS + required: false + type: Array + value: TZS + - displayName: UAH + required: false + type: Array + value: UAH + - displayName: UGX + required: false + type: Array + value: UGX + - displayName: USD + required: false + type: Array + value: USD + - displayName: UYU + required: false + type: Array + value: UYU + - displayName: UZS + required: false + type: Array + value: UZS + - displayName: VEF + required: false + type: Array + value: VEF + - displayName: VND + required: false + type: Array + value: VND + - displayName: VUV + required: false + type: Array + value: VUV + - displayName: WST + required: false + type: Array + value: WST + - displayName: XAF + required: false + type: Array + value: XAF + - displayName: XCD + required: false + type: Array + value: XCD + - displayName: XDR + required: false + type: Array + value: XDR + - displayName: XOF + required: false + type: Array + value: XOF + - displayName: XPF + required: false + type: Array + value: XPF + - displayName: YER + required: false + type: Array + value: YER + - displayName: ZAR + required: false + type: Array + value: ZAR + - displayName: ZMW + required: false + type: Array + value: ZMW + - displayName: ZWD + required: false + type: Array + value: ZWD + required: false + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid email. + field: EmailAddress + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Addresses.Line1 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 11 characters + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing + required: false + type: String + value: Billing + - displayName: Delivery + required: false + type: String + value: Delivery + required: true + type: String + required: false + type: Array + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 25 characters + field: ContactName + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + address: + description: The address for the contact + displayName: Address + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Address.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Address.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Address.Line1 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 11 characters + field: Address.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Address.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing + required: false + type: String + value: Billing + - displayName: Delivery + required: false + type: String + value: Delivery + - displayName: Unknown + required: false + type: String + value: Unknown + required: true + type: String + required: true + type: Object + email: + description: The email address for the contact + displayName: Email + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: Contacts.Email + name: + description: The name of the contact + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 25 characters + field: Contacts.Name + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 21 characters + field: Phone.Number + type: + description: The type of phone number + displayName: Phone Type + options: + - displayName: Unknown + required: false + type: String + value: Unknown + - displayName: Fax + required: false + type: String + value: Fax + required: false + type: String + validation: + information: + - details: Do not set or set to Unknown for phone numbers; set to Fax for fax number + field: Phone.Type + warnings: [] + required: false + type: Array + validation: + information: [] + warnings: + - details: Must contain a maximum of 3 phone numbers + field: Contacts.Phone + - details: Must contain a maximum of 1 fax number + field: Contacts.Phone + required: false + type: Array + validation: + information: [] + warnings: + - details: Must have at most five contacts + field: Contacts + - details: Must have at least one piece of contact information + field: Contacts + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 50 characters + field: CustomerName + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 255 characters + field: EmailAddress + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 21 characters + field: Phone + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid ABN (Australian Business Number) in the format XX XXX XXX XXX + field: RegistrationNumber + - details: Must have a length of 14 characters + field: RegistrationNumber + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must have a length between 1 and 19 characters + field: TaxNumber + required: true + type: Object + Oracle NetSuite: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a two letter Country ISO code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing + required: false + type: String + value: Billing + - displayName: Delivery + required: false + type: String + value: Delivery + - displayName: Unknown + required: false + type: String + value: Unknown + required: true + type: String + required: false + type: Array + validation: + information: + - details: Multiple addresses of Unknown type may be provided + field: Addresses + warnings: + - details: Only one each of Billing and Delivery addresses can be provided + field: Addresses + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + email: + description: The email address for the contact + displayName: Email + required: false + type: String + name: + description: The name of the contact + displayName: Name + required: true + type: String + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + type: + description: The type of phone number + displayName: Phone Type + required: true + type: String + required: false + type: Array + validation: + information: [] + warnings: + - details: Must be a maximum of four distinct number types + field: Contacts.Phone + status: + description: The current state of the contact + displayName: Contact Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + required: false + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 13 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 21 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: true + type: String + validation: + information: + - details: Only 1 address each of type(s) Billing/Delivery may be specified. + field: Addresses.Type + warnings: [] + required: false + type: Array + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 25 characters for first and last names + field: ContactName + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: CustomerName + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the base currency of the QuickBooks Desktop company + field: DefaultCurrency + warnings: + - details: Must be a three letter ISO code that matches an existing active currency in the QuickBooks Desktop company + field: DefaultCurrency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: DefaultCurrency + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 21 characters + field: Phone + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 15 characters. + field: RegistrationNumber + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 30 characters. + field: TaxNumber + required: true + type: Object + QuickBooks Online: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: Addresses.PostalCode + - details: Max length of 50 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 225 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: false + type: String + validation: + information: [] + warnings: + - details: Billing = POBOX, Delivery/Unknown = DELIVERY + field: Addresses.Type + required: false + type: Array + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + type: + description: The type of phone number + displayName: Phone Type + required: true + type: String + required: false + type: Array + required: false + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + validation: + information: [] + warnings: + - details: Names must be unique across customers, suppliers and employees + field: CustomerName + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Default currency can only differ from the base company currency if multi-currency is enabled for the company. + field: DefaultCurrency + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: Phone + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: Addresses.PostalCode + - details: Max length of 50 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 225 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: false + type: String + validation: + information: [] + warnings: + - details: Billing = POBOX, Delivery/Unknown = DELIVERY + field: Addresses.Type + required: false + type: Array + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + type: + description: The type of phone number + displayName: Phone Type + required: true + type: String + required: false + type: Array + required: false + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + validation: + information: [] + warnings: + - details: Names must be unique across customers, suppliers and employees + field: CustomerName + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Default currency can only differ from the base company currency if multi-currency is enabled for the company. + field: DefaultCurrency + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: Phone + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Sage 50 (UK): + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: Contact addresses for the customer. + displayName: Addresses + properties: + city: + description: The city of the customer address. + displayName: City + required: false + type: String + countryCode: + description: The country code of the customer address + displayName: Country Code + required: true + type: String + validation: + information: + - details: XX is a valid country code for 'Unknown Country' + warnings: + - details: The country code must be a valid ISO 3166 value + line1: + description: Line 1 of the customer address. + displayName: Line 1 + required: true + type: String + line2: + description: Line 2 of the customer address. + displayName: Line 2 + required: false + type: String + postalCode: + description: Post or Zip code for the address. + displayName: Postal code + required: false + type: String + region: + description: The region of the customer address. + displayName: Region + required: false + type: String + type: + description: The type of address as it related to the customer. + displayName: Type + options: + - displayName: Delivery Address + required: false + type: String + value: Delivery + - displayName: Unknown Address + required: false + type: String + value: Unknown + required: false + type: String + validation: + information: + - details: If the address is available in 'SALES_DEL_ADDR' table then the address type will be Delivery. All others will default to type 'Unknown' + field: addresses.type + warnings: [] + required: false + type: Array + validation: + information: [] + warnings: + - details: Only one address can be included in the Addresses array. + field: addresses + contactName: + description: The name of the main contact for the customer. + displayName: Contact Name + required: false + type: String + validation: + information: [] + warnings: + - details: The contact name can have a maximum of 30 characters + field: contactName + customerName: + description: Name of the customer. + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: The customer name can have a maximum of 60 characters + field: customerName + defaultCurrency: + description: The currency in which the customer will operate. + displayName: Default Currency + required: false + type: String + validation: + information: + - details: If not provided, the currency will default to the company's base currency. + field: defaultCurrency + warnings: [] + emailAddress: + description: The email address that the customer may be contacted on. + displayName: Email Address + required: false + type: String + validation: + information: [] + warnings: + - details: The email address can have a maximum of 255 characters + field: emailAddress + id: + description: ID of the customer. + displayName: Id + required: true + type: String + validation: + information: + - details: The customer ID must be all Uppercase, if it is not, it will be converted to Uppercase before pushing. + field: id + warnings: + - details: The customer ID must be unique, contain no spaces and have a maximum of 8 characters. + field: id + phone: + description: The telephone number that the customer may be contacted on. + displayName: Telephone + required: false + type: String + validation: + information: [] + warnings: + - details: The phone can have a maximum of 30 characters + field: phone + status: + description: The status of the customer. + displayName: Status + options: + - displayName: Active Status + required: false + type: String + value: Active + - displayName: Archived Status + required: false + type: String + value: Archived + required: false + type: String + taxNumber: + description: Legal company registration identifier. + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: The tax number can have a maximum of 20 characters + field: taxNumber + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + options: + - displayName: Afghanistan (AF) + required: false + type: String + value: Afghanistan (AF) + - displayName: Albania (AL) + required: false + type: String + value: Albania (AL) + - displayName: Algeria (DZ) + required: false + type: String + value: Algeria (DZ) + - displayName: Andorra (AD) + required: false + type: String + value: Andorra (AD) + - displayName: Angola (AO) + required: false + type: String + value: Angola (AO) + - displayName: Argentina (AR) + required: false + type: String + value: Argentina (AR) + - displayName: Armenia (AM) + required: false + type: String + value: Armenia (AM) + - displayName: Aruba (AW) + required: false + type: String + value: Aruba (AW) + - displayName: Australia (AU) + required: false + type: String + value: Australia (AU) + - displayName: Austria (AT) + required: false + type: String + value: Austria (AT) + - displayName: Azerbaijan (AZ) + required: false + type: String + value: Azerbaijan (AZ) + - displayName: Bahamas (BS) + required: false + type: String + value: Bahamas (BS) + - displayName: Bahrain (BH) + required: false + type: String + value: Bahrain (BH) + - displayName: Bangladesh (BD) + required: false + type: String + value: Bangladesh (BD) + - displayName: Barbados (BB) + required: false + type: String + value: Barbados (BB) + - displayName: Belarus (BY) + required: false + type: String + value: Belarus (BY) + - displayName: Belgium (BE) + required: false + type: String + value: Belgium (BE) + - displayName: Belize (BZ) + required: false + type: String + value: Belize (BZ) + - displayName: Benin (BJ) + required: false + type: String + value: Benin (BJ) + - displayName: Bermuda (BM) + required: false + type: String + value: Bermuda (BM) + - displayName: Bhutan (BT) + required: false + type: String + value: Bhutan (BT) + - displayName: Bolivia (BO) + required: false + type: String + value: Bolivia (BO) + - displayName: Bosnia and Herzegovina (BA) + required: false + type: String + value: Bosnia and Herzegovina (BA) + - displayName: Botswana (BW) + required: false + type: String + value: Botswana (BW) + - displayName: Brazil (BR) + required: false + type: String + value: Brazil (BR) + - displayName: British Virgin Islands (VG) + required: false + type: String + value: British Virgin Islands (VG) + - displayName: Brunei Darussalam (BN) + required: false + type: String + value: Brunei Darussalam (BN) + - displayName: Bulgaria (BG) + required: false + type: String + value: Bulgaria (BG) + - displayName: Burkina Faso (BF) + required: false + type: String + value: Burkina Faso (BF) + - displayName: Burundi (BI) + required: false + type: String + value: Burundi (BI) + - displayName: Cambodia (KH) + required: false + type: String + value: Cambodia (KH) + - displayName: Cameroon (CM) + required: false + type: String + value: Cameroon (CM) + - displayName: Canada (CA) + required: false + type: String + value: Canada (CA) + - displayName: Cape Verde (CV) + required: false + type: String + value: Cape Verde (CV) + - displayName: Cayman Islands (KY) + required: false + type: String + value: Cayman Islands (KY) + - displayName: Central African Republic (CF) + required: false + type: String + value: Central African Republic (CF) + - displayName: Chad (TD) + required: false + type: String + value: Chad (TD) + - displayName: Chile (CL) + required: false + type: String + value: Chile (CL) + - displayName: China (CN) + required: false + type: String + value: China (CN) + - displayName: Colombia (CO) + required: false + type: String + value: Colombia (CO) + - displayName: Comoros (KM) + required: false + type: String + value: Comoros (KM) + - displayName: Congo (CG) + required: false + type: String + value: Congo (CG) + - displayName: Costa Rica (CR) + required: false + type: String + value: Costa Rica (CR) + - displayName: Croatia (HR) + required: false + type: String + value: Croatia (HR) + - displayName: Cuba (CU) + required: false + type: String + value: Cuba (CU) + - displayName: Cura�ao (CW) + required: false + type: String + value: Cura�ao (CW) + - displayName: Cyprus (CY) + required: false + type: String + value: Cyprus (CY) + - displayName: Czech Republic (CZ) + required: false + type: String + value: Czech Republic (CZ) + - displayName: Democratic Republic of the Congo (CD) + required: false + type: String + value: Democratic Republic of the Congo (CD) + - displayName: Denmark (DK) + required: false + type: String + value: Denmark (DK) + - displayName: Djibouti (DJ) + required: false + type: String + value: Djibouti (DJ) + - displayName: Dominica (DM) + required: false + type: String + value: Dominica (DM) + - displayName: Dominican Republic (DO) + required: false + type: String + value: Dominican Republic (DO) + - displayName: East Timor (TP) + required: false + type: String + value: East Timor (TP) + - displayName: Ecuador (EC) + required: false + type: String + value: Ecuador (EC) + - displayName: Egypt (EG) + required: false + type: String + value: Egypt (EG) + - displayName: El Salvador (SV) + required: false + type: String + value: El Salvador (SV) + - displayName: Equatorial Guinea (GQ) + required: false + type: String + value: Equatorial Guinea (GQ) + - displayName: Eritrea (ER) + required: false + type: String + value: Eritrea (ER) + - displayName: Estonia (EE) + required: false + type: String + value: Estonia (EE) + - displayName: Ethiopia (ET) + required: false + type: String + value: Ethiopia (ET) + - displayName: Falkland Islands (Malvinas) (FK) + required: false + type: String + value: Falkland Islands (Malvinas) (FK) + - displayName: Federated States of Micronesia (FM) + required: false + type: String + value: Federated States of Micronesia (FM) + - displayName: Fiji (FJ) + required: false + type: String + value: Fiji (FJ) + - displayName: Finland (FI) + required: false + type: String + value: Finland (FI) + - displayName: France (FR) + required: false + type: String + value: France (FR) + - displayName: French Polynesia (PF) + required: false + type: String + value: French Polynesia (PF) + - displayName: Gabon (GA) + required: false + type: String + value: Gabon (GA) + - displayName: Gambia (GM) + required: false + type: String + value: Gambia (GM) + - displayName: Georgia (GE) + required: false + type: String + value: Georgia (GE) + - displayName: Germany (DE) + required: false + type: String + value: Germany (DE) + - displayName: Ghana (GH) + required: false + type: String + value: Ghana (GH) + - displayName: Gibraltar (GI) + required: false + type: String + value: Gibraltar (GI) + - displayName: Greece (GR) + required: false + type: String + value: Greece (GR) + - displayName: Greenland (GL) + required: false + type: String + value: Greenland (GL) + - displayName: Grenada (GD) + required: false + type: String + value: Grenada (GD) + - displayName: Guadaloupe (GP) + required: false + type: String + value: Guadaloupe (GP) + - displayName: Guam (GU) + required: false + type: String + value: Guam (GU) + - displayName: Guatemala (GT) + required: false + type: String + value: Guatemala (GT) + - displayName: Guernsey (GG) + required: false + type: String + value: Guernsey (GG) + - displayName: Guinea (GN) + required: false + type: String + value: Guinea (GN) + - displayName: Guinea-Bissau (GW) + required: false + type: String + value: Guinea-Bissau (GW) + - displayName: Guyana (GY) + required: false + type: String + value: Guyana (GY) + - displayName: Haiti (HT) + required: false + type: String + value: Haiti (HT) + - displayName: Honduras (HN) + required: false + type: String + value: Honduras (HN) + - displayName: Hong Kong (HK) + required: false + type: String + value: Hong Kong (HK) + - displayName: Hungary (HU) + required: false + type: String + value: Hungary (HU) + - displayName: Iceland (IS) + required: false + type: String + value: Iceland (IS) + - displayName: India (IN) + required: false + type: String + value: India (IN) + - displayName: Indonesia (ID) + required: false + type: String + value: Indonesia (ID) + - displayName: Iran (IR) + required: false + type: String + value: Iran (IR) + - displayName: Iraq (IQ) + required: false + type: String + value: Iraq (IQ) + - displayName: Ireland (IE) + required: false + type: String + value: Ireland (IE) + - displayName: Israel (IL) + required: false + type: String + value: Israel (IL) + - displayName: Italy (IT) + required: false + type: String + value: Italy (IT) + - displayName: Ivory Coast (CI) + required: false + type: String + value: Ivory Coast (CI) + - displayName: Jamaica (JM) + required: false + type: String + value: Jamaica (JM) + - displayName: Japan (JP) + required: false + type: String + value: Japan (JP) + - displayName: Jersey (JE) + required: false + type: String + value: Jersey (JE) + - displayName: Jordan (JO) + required: false + type: String + value: Jordan (JO) + - displayName: Kazakhstan (KZ) + required: false + type: String + value: Kazakhstan (KZ) + - displayName: Kenya (KE) + required: false + type: String + value: Kenya (KE) + - displayName: Kuwait (KW) + required: false + type: String + value: Kuwait (KW) + - displayName: Kyrgyzstan (KG) + required: false + type: String + value: Kyrgyzstan (KG) + - displayName: Laos (LA) + required: false + type: String + value: Laos (LA) + - displayName: Latvia (LV) + required: false + type: String + value: Latvia (LV) + - displayName: Lebanon (LB) + required: false + type: String + value: Lebanon (LB) + - displayName: Lesotho (LS) + required: false + type: String + value: Lesotho (LS) + - displayName: Liberia (LR) + required: false + type: String + value: Liberia (LR) + - displayName: Libya (LY) + required: false + type: String + value: Libya (LY) + - displayName: Liechtenstein (LI) + required: false + type: String + value: Liechtenstein (LI) + - displayName: Lithuania (LT) + required: false + type: String + value: Lithuania (LT) + - displayName: Luxembourg (LU) + required: false + type: String + value: Luxembourg (LU) + - displayName: Macau (MO) + required: false + type: String + value: Macau (MO) + - displayName: Macedonia (MK) + required: false + type: String + value: Macedonia (MK) + - displayName: Madagascar (MG) + required: false + type: String + value: Madagascar (MG) + - displayName: Malawi (MW) + required: false + type: String + value: Malawi (MW) + - displayName: Malaysia (MY) + required: false + type: String + value: Malaysia (MY) + - displayName: Maldives (MV) + required: false + type: String + value: Maldives (MV) + - displayName: Mali (ML) + required: false + type: String + value: Mali (ML) + - displayName: Malta (MT) + required: false + type: String + value: Malta (MT) + - displayName: Mauritania (MR) + required: false + type: String + value: Mauritania (MR) + - displayName: Mauritius (MU) + required: false + type: String + value: Mauritius (MU) + - displayName: Mexico (MX) + required: false + type: String + value: Mexico (MX) + - displayName: Moldova (MD) + required: false + type: String + value: Moldova (MD) + - displayName: Monaco (MC) + required: false + type: String + value: Monaco (MC) + - displayName: Mongolia (MN) + required: false + type: String + value: Mongolia (MN) + - displayName: Montenegro (ME) + required: false + type: String + value: Montenegro (ME) + - displayName: Morocco (MA) + required: false + type: String + value: Morocco (MA) + - displayName: Mozambique (MZ) + required: false + type: String + value: Mozambique (MZ) + - displayName: Myanmar (MM) + required: false + type: String + value: Myanmar (MM) + - displayName: Namibia (NA) + required: false + type: String + value: Namibia (NA) + - displayName: Nepal (NP) + required: false + type: String + value: Nepal (NP) + - displayName: Netherlands (NL) + required: false + type: String + value: Netherlands (NL) + - displayName: Netherlands Antilles (AN) + required: false + type: String + value: Netherlands Antilles (AN) + - displayName: New Caledonia (NC) + required: false + type: String + value: New Caledonia (NC) + - displayName: New Zealand (NZ) + required: false + type: String + value: New Zealand (NZ) + - displayName: Nicaragua (NI) + required: false + type: String + value: Nicaragua (NI) + - displayName: Niger (NE) + required: false + type: String + value: Niger (NE) + - displayName: Nigeria (NG) + required: false + type: String + value: Nigeria (NG) + - displayName: North Korea (KP) + required: false + type: String + value: North Korea (KP) + - displayName: Norway (NO) + required: false + type: String + value: Norway (NO) + - displayName: Oman (OM) + required: false + type: String + value: Oman (OM) + - displayName: Pakistan (PK) + required: false + type: String + value: Pakistan (PK) + - displayName: Panama (PA) + required: false + type: String + value: Panama (PA) + - displayName: Papua New Guinea (PG) + required: false + type: String + value: Papua New Guinea (PG) + - displayName: Paraguay (PY) + required: false + type: String + value: Paraguay (PY) + - displayName: Peru (PE) + required: false + type: String + value: Peru (PE) + - displayName: Philippines (PH) + required: false + type: String + value: Philippines (PH) + - displayName: Poland (PL) + required: false + type: String + value: Poland (PL) + - displayName: Portugal (PT) + required: false + type: String + value: Portugal (PT) + - displayName: Puerto Rico (PR) + required: false + type: String + value: Puerto Rico (PR) + - displayName: Qatar (QA) + required: false + type: String + value: Qatar (QA) + - displayName: Romania (RO) + required: false + type: String + value: Romania (RO) + - displayName: Russia (RU) + required: false + type: String + value: Russia (RU) + - displayName: Rwanda (RW) + required: false + type: String + value: Rwanda (RW) + - displayName: Saint Kitts and Nevis (KN) + required: false + type: String + value: Saint Kitts and Nevis (KN) + - displayName: Saint Pierre and Miquelon (PM) + required: false + type: String + value: Saint Pierre and Miquelon (PM) + - displayName: Samoa (WS) + required: false + type: String + value: Samoa (WS) + - displayName: San Marino (SM) + required: false + type: String + value: San Marino (SM) + - displayName: Sao Tome and Principe (ST) + required: false + type: String + value: Sao Tome and Principe (ST) + - displayName: Saudi Arabia (SA) + required: false + type: String + value: Saudi Arabia (SA) + - displayName: Senegal (SN) + required: false + type: String + value: Senegal (SN) + - displayName: Serbia (RS) + required: false + type: String + value: Serbia (RS) + - displayName: Seychelles (SC) + required: false + type: String + value: Seychelles (SC) + - displayName: Sierra Leone (SL) + required: false + type: String + value: Sierra Leone (SL) + - displayName: Singapore (SG) + required: false + type: String + value: Singapore (SG) + - displayName: Slovakia (SK) + required: false + type: String + value: Slovakia (SK) + - displayName: Slovenia (SI) + required: false + type: String + value: Slovenia (SI) + - displayName: Solomon Islands (SB) + required: false + type: String + value: Solomon Islands (SB) + - displayName: Somalia (SO) + required: false + type: String + value: Somalia (SO) + - displayName: South Africa (ZA) + required: false + type: String + value: South Africa (ZA) + - displayName: South Korea (KR) + required: false + type: String + value: South Korea (KR) + - displayName: Spain (ES) + required: false + type: String + value: Spain (ES) + - displayName: Sri Lanka (LK) + required: false + type: String + value: Sri Lanka (LK) + - displayName: St. Lucia (LC) + required: false + type: String + value: St. Lucia (LC) + - displayName: Sudan (SD) + required: false + type: String + value: Sudan (SD) + - displayName: Surinam (SR) + required: false + type: String + value: Surinam (SR) + - displayName: Swaziland (SZ) + required: false + type: String + value: Swaziland (SZ) + - displayName: Sweden (SE) + required: false + type: String + value: Sweden (SE) + - displayName: Switzerland (CH) + required: false + type: String + value: Switzerland (CH) + - displayName: Syria (SY) + required: false + type: String + value: Syria (SY) + - displayName: Taiwan (TW) + required: false + type: String + value: Taiwan (TW) + - displayName: Tajikistan (TJ) + required: false + type: String + value: Tajikistan (TJ) + - displayName: Tanzania (TZ) + required: false + type: String + value: Tanzania (TZ) + - displayName: Thailand (TH) + required: false + type: String + value: Thailand (TH) + - displayName: Togo (TG) + required: false + type: String + value: Togo (TG) + - displayName: Tonga (TO) + required: false + type: String + value: Tonga (TO) + - displayName: Trinidad and Tobago (TT) + required: false + type: String + value: Trinidad and Tobago (TT) + - displayName: Tunisia (TN) + required: false + type: String + value: Tunisia (TN) + - displayName: Turkey (TR) + required: false + type: String + value: Turkey (TR) + - displayName: Turkmenistan (TM) + required: false + type: String + value: Turkmenistan (TM) + - displayName: Tuvalu (TV) + required: false + type: String + value: Tuvalu (TV) + - displayName: Uganda (UG) + required: false + type: String + value: Uganda (UG) + - displayName: Ukraine (UA) + required: false + type: String + value: Ukraine (UA) + - displayName: United Arab Emirates (AE) + required: false + type: String + value: United Arab Emirates (AE) + - displayName: United Kingdom (GB) + required: false + type: String + value: United Kingdom (GB) + - displayName: United States (US) + required: false + type: String + value: United States (US) + - displayName: Uruguay (UY) + required: false + type: String + value: Uruguay (UY) + - displayName: Uzbekistan (UZ) + required: false + type: String + value: Uzbekistan (UZ) + - displayName: Vanuatu (VU) + required: false + type: String + value: Vanuatu (VU) + - displayName: Venezuela (VE) + required: false + type: String + value: Venezuela (VE) + - displayName: Vietnam (VN) + required: false + type: String + value: Vietnam (VN) + - displayName: Virgin Islands U.S. (VI) + required: false + type: String + value: Virgin Islands U.S. (VI) + - displayName: Western Sahara (EH) + required: false + type: String + value: Western Sahara (EH) + - displayName: Yemen (YE) + required: false + type: String + value: Yemen (YE) + - displayName: Zaire (ZR) + required: false + type: String + value: Zaire (ZR) + - displayName: Zambia (ZM) + required: false + type: String + value: Zambia (ZM) + - displayName: Zimbabwe (ZW) + required: false + type: String + value: Zimbabwe (ZW) + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + validation: + information: [] + warnings: + - details: If you're adding an address for this customer, you must also include the first line + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Can contain a maximum of two addresses; main address and delivery address + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: false + type: String + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: false + type: String + validation: + information: + - details: If Customer.DefaultCurrency is not provided; will be mapped from company base currency + field: DefaultCurrency + warnings: [] + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Sage Intacct: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 80 characters + field: Addresses.City + country: + description: The country for the address + displayName: Country + options: + - displayName: United States + required: false + type: String + value: United States + - displayName: Afghanistan + required: false + type: String + value: Afghanistan + - displayName: Aland Islands + required: false + type: String + value: Aland Islands + - displayName: Albania + required: false + type: String + value: Albania + - displayName: Algeria + required: false + type: String + value: Algeria + - displayName: American Samoa + required: false + type: String + value: American Samoa + - displayName: Andorra + required: false + type: String + value: Andorra + - displayName: Angola + required: false + type: String + value: Angola + - displayName: Anguilla + required: false + type: String + value: Anguilla + - displayName: Antarctica + required: false + type: String + value: Antarctica + - displayName: Antigua and Barbuda + required: false + type: String + value: Antigua and Barbuda + - displayName: Argentina + required: false + type: String + value: Argentina + - displayName: Armenia + required: false + type: String + value: Armenia + - displayName: Aruba + required: false + type: String + value: Aruba + - displayName: Australia + required: false + type: String + value: Australia + - displayName: Austria + required: false + type: String + value: Austria + - displayName: Azerbaijan + required: false + type: String + value: Azerbaijan + - displayName: Bahamas + required: false + type: String + value: Bahamas + - displayName: Bahrain + required: false + type: String + value: Bahrain + - displayName: Bangladesh + required: false + type: String + value: Bangladesh + - displayName: Barbados + required: false + type: String + value: Barbados + - displayName: Belarus + required: false + type: String + value: Belarus + - displayName: Belgium + required: false + type: String + value: Belgium + - displayName: Belize + required: false + type: String + value: Belize + - displayName: Benin + required: false + type: String + value: Benin + - displayName: Bermuda + required: false + type: String + value: Bermuda + - displayName: Bhutan + required: false + type: String + value: Bhutan + - displayName: Bolivia + required: false + type: String + value: Bolivia + - displayName: Bonaire, Sint Eustatius and Saba + required: false + type: String + value: Bonaire, Sint Eustatius and Saba + - displayName: Bosnia and Herzegovina + required: false + type: String + value: Bosnia and Herzegovina + - displayName: Botswana + required: false + type: String + value: Botswana + - displayName: Bouvet Island + required: false + type: String + value: Bouvet Island + - displayName: Brazil + required: false + type: String + value: Brazil + - displayName: British Indian Ocean Territory + required: false + type: String + value: British Indian Ocean Territory + - displayName: Brunei Darussalam + required: false + type: String + value: Brunei Darussalam + - displayName: Bulgaria + required: false + type: String + value: Bulgaria + - displayName: Burkina Faso + required: false + type: String + value: Burkina Faso + - displayName: Burundi + required: false + type: String + value: Burundi + - displayName: Cambodia + required: false + type: String + value: Cambodia + - displayName: Cameroon + required: false + type: String + value: Cameroon + - displayName: Canada + required: false + type: String + value: Canada + - displayName: Cape Verde + required: false + type: String + value: Cape Verde + - displayName: Cayman Islands + required: false + type: String + value: Cayman Islands + - displayName: Central African Republic + required: false + type: String + value: Central African Republic + - displayName: Chad + required: false + type: String + value: Chad + - displayName: Chile + required: false + type: String + value: Chile + - displayName: China + required: false + type: String + value: China + - displayName: Christmas Island + required: false + type: String + value: Christmas Island + - displayName: Cocos (Keeling) Islands + required: false + type: String + value: Cocos (Keeling) Islands + - displayName: Colombia + required: false + type: String + value: Colombia + - displayName: Comoros + required: false + type: String + value: Comoros + - displayName: Congo + required: false + type: String + value: Congo + - displayName: Congo, Democratic Republic + required: false + type: String + value: Congo, Democratic Republic + - displayName: Cook Islands + required: false + type: String + value: Cook Islands + - displayName: Costa Rica + required: false + type: String + value: Costa Rica + - displayName: C�te d'Ivoire + required: false + type: String + value: C�te d'Ivoire + - displayName: Croatia + required: false + type: String + value: Croatia + - displayName: Cuba + required: false + type: String + value: Cuba + - displayName: Cura�ao + required: false + type: String + value: Cura�ao + - displayName: Cyprus + required: false + type: String + value: Cyprus + - displayName: Czech Republic + required: false + type: String + value: Czech Republic + - displayName: Denmark + required: false + type: String + value: Denmark + - displayName: Djibouti + required: false + type: String + value: Djibouti + - displayName: Dominica + required: false + type: String + value: Dominica + - displayName: Dominican Republic + required: false + type: String + value: Dominican Republic + - displayName: Ecuador + required: false + type: String + value: Ecuador + - displayName: Egypt + required: false + type: String + value: Egypt + - displayName: El Salvador + required: false + type: String + value: El Salvador + - displayName: Equatorial Guinea + required: false + type: String + value: Equatorial Guinea + - displayName: Eritrea + required: false + type: String + value: Eritrea + - displayName: Estonia + required: false + type: String + value: Estonia + - displayName: Eswatini + required: false + type: String + value: Eswatini + - displayName: Ethiopia + required: false + type: String + value: Ethiopia + - displayName: Falkland Islands (Malvinas + required: false + type: String + value: Falkland Islands (Malvinas + - displayName: Faroe Islands + required: false + type: String + value: Faroe Islands + - displayName: Fiji + required: false + type: String + value: Fiji + - displayName: Finland + required: false + type: String + value: Finland + - displayName: France + required: false + type: String + value: France + - displayName: French Guiana + required: false + type: String + value: French Guiana + - displayName: French Polynesia + required: false + type: String + value: French Polynesia + - displayName: French Southern Territories + required: false + type: String + value: French Southern Territories + - displayName: Gabon + required: false + type: String + value: Gabon + - displayName: Gambia + required: false + type: String + value: Gambia + - displayName: Georgia + required: false + type: String + value: Georgia + - displayName: Germany + required: false + type: String + value: Germany + - displayName: Ghana + required: false + type: String + value: Ghana + - displayName: Gibraltar + required: false + type: String + value: Gibraltar + - displayName: Greece + required: false + type: String + value: Greece + - displayName: Greenland + required: false + type: String + value: Greenland + - displayName: Grenada + required: false + type: String + value: Grenada + - displayName: Guadeloupe + required: false + type: String + value: Guadeloupe + - displayName: Guam + required: false + type: String + value: Guam + - displayName: Guatemala + required: false + type: String + value: Guatemala + - displayName: Guernsey + required: false + type: String + value: Guernsey + - displayName: Guinea + required: false + type: String + value: Guinea + - displayName: Guinea-Bissau + required: false + type: String + value: Guinea-Bissau + - displayName: Guyana + required: false + type: String + value: Guyana + - displayName: Haiti + required: false + type: String + value: Haiti + - displayName: Heard Is. & Mcdonald Islands + required: false + type: String + value: Heard Is. & Mcdonald Islands + - displayName: Honduras + required: false + type: String + value: Honduras + - displayName: Hong Kong + required: false + type: String + value: Hong Kong + - displayName: Hungary + required: false + type: String + value: Hungary + - displayName: Iceland + required: false + type: String + value: Iceland + - displayName: India + required: false + type: String + value: India + - displayName: Indonesia + required: false + type: String + value: Indonesia + - displayName: Iran, Islamic Republic of + required: false + type: String + value: Iran, Islamic Republic of + - displayName: Iraq + required: false + type: String + value: Iraq + - displayName: Ireland + required: false + type: String + value: Ireland + - displayName: Isle of Man + required: false + type: String + value: Isle of Man + - displayName: Israel + required: false + type: String + value: Israel + - displayName: Italy + required: false + type: String + value: Italy + - displayName: Jamaica + required: false + type: String + value: Jamaica + - displayName: Japan + required: false + type: String + value: Japan + - displayName: Jersey + required: false + type: String + value: Jersey + - displayName: Jordan + required: false + type: String + value: Jordan + - displayName: Kazakhstan + required: false + type: String + value: Kazakhstan + - displayName: Kenya + required: false + type: String + value: Kenya + - displayName: Kiribati + required: false + type: String + value: Kiribati + - displayName: Korea, Republic of + required: false + type: String + value: Korea, Republic of + - displayName: Korea, Demo. People's Rep + required: false + type: String + value: Korea, Demo. People's Rep + - displayName: Kosovo + required: false + type: String + value: Kosovo + - displayName: Kuwait + required: false + type: String + value: Kuwait + - displayName: Kyrgyzstan + required: false + type: String + value: Kyrgyzstan + - displayName: Lao + required: false + type: String + value: Lao + - displayName: Latvia + required: false + type: String + value: Latvia + - displayName: Lebanon + required: false + type: String + value: Lebanon + - displayName: Lesotho + required: false + type: String + value: Lesotho + - displayName: Liberia + required: false + type: String + value: Liberia + - displayName: Libyan Arab Jamahiriya + required: false + type: String + value: Libyan Arab Jamahiriya + - displayName: Liechtenstein + required: false + type: String + value: Liechtenstein + - displayName: Lithuania + required: false + type: String + value: Lithuania + - displayName: Luxembourg + required: false + type: String + value: Luxembourg + - displayName: Macao + required: false + type: String + value: Macao + - displayName: Macedonia + required: false + type: String + value: Macedonia + - displayName: Madagascar + required: false + type: String + value: Madagascar + - displayName: Malawi + required: false + type: String + value: Malawi + - displayName: Malaysia + required: false + type: String + value: Malaysia + - displayName: Maldives + required: false + type: String + value: Maldives + - displayName: Mali + required: false + type: String + value: Mali + - displayName: Malta + required: false + type: String + value: Malta + - displayName: Marshall Islands + required: false + type: String + value: Marshall Islands + - displayName: Martinique + required: false + type: String + value: Martinique + - displayName: Mauritania + required: false + type: String + value: Mauritania + - displayName: Mauritius + required: false + type: String + value: Mauritius + - displayName: Mayotte + required: false + type: String + value: Mayotte + - displayName: Mexico + required: false + type: String + value: Mexico + - displayName: Micronesia + required: false + type: String + value: Micronesia + - displayName: Moldova, Republic of + required: false + type: String + value: Moldova, Republic of + - displayName: Monaco + required: false + type: String + value: Monaco + - displayName: Mongolia + required: false + type: String + value: Mongolia + - displayName: Montenegro + required: false + type: String + value: Montenegro + - displayName: Montserrat + required: false + type: String + value: Montserrat + - displayName: Morocco + required: false + type: String + value: Morocco + - displayName: Mozambique + required: false + type: String + value: Mozambique + - displayName: Myanmar + required: false + type: String + value: Myanmar + - displayName: Namibia + required: false + type: String + value: Namibia + - displayName: Nauru + required: false + type: String + value: Nauru + - displayName: Nepal + required: false + type: String + value: Nepal + - displayName: Netherlands + required: false + type: String + value: Netherlands + - displayName: Netherlands Antilles + required: false + type: String + value: Netherlands Antilles + - displayName: New Caledonia + required: false + type: String + value: New Caledonia + - displayName: New Zealand + required: false + type: String + value: New Zealand + - displayName: Nicaragua + required: false + type: String + value: Nicaragua + - displayName: Niger + required: false + type: String + value: Niger + - displayName: Nigeria + required: false + type: String + value: Nigeria + - displayName: Niue + required: false + type: String + value: Niue + - displayName: Norfolk Island + required: false + type: String + value: Norfolk Island + - displayName: Northern Mariana Islands + required: false + type: String + value: Northern Mariana Islands + - displayName: Norway + required: false + type: String + value: Norway + - displayName: Oman + required: false + type: String + value: Oman + - displayName: Pakistan + required: false + type: String + value: Pakistan + - displayName: Palau + required: false + type: String + value: Palau + - displayName: Palestinian Territory, Occupied + required: false + type: String + value: Palestinian Territory, Occupied + - displayName: Panama + required: false + type: String + value: Panama + - displayName: Papua New Guinea + required: false + type: String + value: Papua New Guinea + - displayName: Paraguay + required: false + type: String + value: Paraguay + - displayName: Peru + required: false + type: String + value: Peru + - displayName: Philippines + required: false + type: String + value: Philippines + - displayName: Pitcairn + required: false + type: String + value: Pitcairn + - displayName: Poland + required: false + type: String + value: Poland + - displayName: Portugal + required: false + type: String + value: Portugal + - displayName: Puerto Rico + required: false + type: String + value: Puerto Rico + - displayName: Qatar + required: false + type: String + value: Qatar + - displayName: Reunion + required: false + type: String + value: Reunion + - displayName: Romania + required: false + type: String + value: Romania + - displayName: Russian Federation + required: false + type: String + value: Russian Federation + - displayName: Rwanda + required: false + type: String + value: Rwanda + - displayName: Saint Barthelemy + required: false + type: String + value: Saint Barthelemy + - displayName: Saint Helena + required: false + type: String + value: Saint Helena + - displayName: Saint Kitts and Nevis + required: false + type: String + value: Saint Kitts and Nevis + - displayName: Saint Lucia + required: false + type: String + value: Saint Lucia + - displayName: Saint Martin + required: false + type: String + value: Saint Martin + - displayName: Saint Pierre and Miquelon + required: false + type: String + value: Saint Pierre and Miquelon + - displayName: Saint Vincent and the Grenadines + required: false + type: String + value: Saint Vincent and the Grenadines + - displayName: Samoa + required: false + type: String + value: Samoa + - displayName: San Marino + required: false + type: String + value: San Marino + - displayName: Sao Tome and Principe + required: false + type: String + value: Sao Tome and Principe + - displayName: Saudi Arabia + required: false + type: String + value: Saudi Arabia + - displayName: Senegal + required: false + type: String + value: Senegal + - displayName: Serbia + required: false + type: String + value: Serbia + - displayName: Seychelles + required: false + type: String + value: Seychelles + - displayName: Sierra Leone + required: false + type: String + value: Sierra Leone + - displayName: Singapore + required: false + type: String + value: Singapore + - displayName: Sint Maarten + required: false + type: String + value: Sint Maarten + - displayName: Slovakia + required: false + type: String + value: Slovakia + - displayName: Slovenia + required: false + type: String + value: Slovenia + - displayName: Solomon Islands + required: false + type: String + value: Solomon Islands + - displayName: Somalia + required: false + type: String + value: Somalia + - displayName: South Africa + required: false + type: String + value: South Africa + - displayName: S. Georgia & S. Sandwich Is + required: false + type: String + value: S. Georgia & S. Sandwich Is + - displayName: Spain + required: false + type: String + value: Spain + - displayName: Sri Lanka + required: false + type: String + value: Sri Lanka + - displayName: Sudan + required: false + type: String + value: Sudan + - displayName: South Sudan + required: false + type: String + value: South Sudan + - displayName: Suriname + required: false + type: String + value: Suriname + - displayName: Svalbard and Jan Mayen + required: false + type: String + value: Svalbard and Jan Mayen + - displayName: Sweden + required: false + type: String + value: Sweden + - displayName: Switzerland + required: false + type: String + value: Switzerland + - displayName: Syrian Arab Republic + required: false + type: String + value: Syrian Arab Republic + - displayName: Taiwan + required: false + type: String + value: Taiwan + - displayName: Tajikistan + required: false + type: String + value: Tajikistan + - displayName: Tanzania, United Republic of + required: false + type: String + value: Tanzania, United Republic of + - displayName: Thailand + required: false + type: String + value: Thailand + - displayName: Timor-Leste + required: false + type: String + value: Timor-Leste + - displayName: Togo + required: false + type: String + value: Togo + - displayName: Tokelau + required: false + type: String + value: Tokelau + - displayName: Tonga + required: false + type: String + value: Tonga + - displayName: Trinidad and Tobago + required: false + type: String + value: Trinidad and Tobago + - displayName: Tunisia + required: false + type: String + value: Tunisia + - displayName: Turkey + required: false + type: String + value: Turkey + - displayName: Turkmenistan + required: false + type: String + value: Turkmenistan + - displayName: Turks and Caicos Islands + required: false + type: String + value: Turks and Caicos Islands + - displayName: Tuvalu + required: false + type: String + value: Tuvalu + - displayName: Uganda + required: false + type: String + value: Uganda + - displayName: Ukraine + required: false + type: String + value: Ukraine + - displayName: United Arab Emirates + required: false + type: String + value: United Arab Emirates + - displayName: United Kingdom + required: false + type: String + value: United Kingdom + - displayName: US Minor Outlying Islands + required: false + type: String + value: US Minor Outlying Islands + - displayName: Uruguay + required: false + type: String + value: Uruguay + - displayName: Uzbekistan + required: false + type: String + value: Uzbekistan + - displayName: Vanuatu + required: false + type: String + value: Vanuatu + - displayName: Vatican City State + required: false + type: String + value: Vatican City State + - displayName: Venezuela + required: false + type: String + value: Venezuela + - displayName: Vietnam + required: false + type: String + value: Vietnam + - displayName: Virgin Islands, British + required: false + type: String + value: Virgin Islands, British + - displayName: Virgin Islands, U.S + required: false + type: String + value: Virgin Islands, U.S + - displayName: Wallis and Futuna + required: false + type: String + value: Wallis and Futuna + - displayName: Western Sahara + required: false + type: String + value: Western Sahara + - displayName: Yemen + required: false + type: String + value: Yemen + - displayName: Zambia + required: false + type: String + value: Zambia + - displayName: Zimbabwe + required: false + type: String + value: Zimbabwe + required: false + type: String + validation: + information: [] + warnings: + - details: Required if TaxNumber is supplied + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 30 characters + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 40 characters + field: Addresses.Region + required: false + type: Array + validation: + information: [] + warnings: + - details: If supplied, must contain only 1 address + field: Addresses + - details: If TaxNumber is supplied, an Address with a Country is required + field: Addresses + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must be between 1 and 200 characters + field: ContactName + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must be between 1 and 100 characters + field: CustomerName + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + - displayName: Canadian Dollar + required: false + type: String + value: CAD + - displayName: Pound Sterling + required: false + type: String + value: GBP + - displayName: US Dollar + required: false + type: String + value: USD + - displayName: Rand + required: false + type: String + value: ZAR + required: false + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: EmailAddress + id: + description: The identifier for the customer, unique for the company + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Required if auto-numbering is not enabled for the Sage Intacct company + field: Id + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 30 characters + field: Phone + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 20 characters + field: TaxNumber + required: true + type: Object + Sandbox: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: true + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: true + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: true + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: true + type: String + type: + description: The type of the address + displayName: Address Type + required: true + type: String + required: true + type: Array + contactName: + description: The name of the main contact for the customer + displayName: Contact Name + required: true + type: String + contacts: + description: A collection of alternative contacts for the customer + displayName: Contacts + properties: + address: + description: The address for the contact + displayName: Address + properties: + city: + description: The third line of the address, or city + displayName: City + required: true + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: true + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: true + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: true + type: String + type: + description: The type of the address + displayName: Address Type + required: true + type: String + required: true + type: Object + email: + description: The email address for the contact + displayName: Email + required: true + type: String + modifiedDate: + description: The date the record was last updated in the system cache + displayName: Modified Date + required: true + type: DateTime + name: + description: The name of the contact + displayName: Name + required: true + type: String + phone: + description: A collection of phone numbers for the contact + displayName: Phone + properties: + number: + description: The full number including country, and area code where applicable + displayName: Number + required: true + type: String + type: + description: The type of phone number + displayName: Phone Type + required: true + type: String + required: true + type: Array + status: + description: The current state of the contact + displayName: Contact Status + required: true + type: String + required: true + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the customer + displayName: Default Currency + required: true + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: true + type: String + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: true + type: String + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: true + type: String + status: + description: The current state of the customer + displayName: Customer Status + required: true + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: true + type: String + required: true + type: Object + Xero: + value: + description: A customer is a person or organisation who buys goods or services + displayName: Customer + properties: + addresses: + description: A collection of addresses associated to the customer + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: Addresses.PostalCode + - details: Max length of 50 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: true + type: String + validation: + information: [] + warnings: + - details: Billing = POBOX, Delivery/Unknown = STREET + field: Addresses.Type + required: false + type: Array + customerName: + description: The name for the customer, typically a company name + displayName: Customer Name + required: true + type: String + emailAddress: + description: The preferred Email address the customer should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the customer should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: Phone + registrationNumber: + description: The customer's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: RegistrationNumber + status: + description: The current state of the customer + displayName: Customer Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Inactive + required: false + type: String + value: InActive + required: false + type: String + taxNumber: + description: The customer's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update customer model + tags: + - Customers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/directCosts": + get: + description: |- + Get create direct cost model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=directCosts) for integrations that support creating direct costs. + operationId: get-create-directCosts-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: "" + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + required: false + type: Object + validation: + information: + - details: is not supported and will be ignored + field: ContactRef + warnings: [] + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: If unspecified, base currency is assumed. Must agree with the bank account in PaymentAllocations + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if the currency is not the base currency + field: CurrencyRate + warnings: [] + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: AccountRef.Name + warnings: [] + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + discountAmount: + description: The value, in the given currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: LineItems.DiscountAmount + warnings: [] + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: LineItems.DiscountPercentage + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + required: false + type: Object + validation: + information: + - details: is not supported and will be ignored + field: LineItems.ItemRef + warnings: [] + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: LineItems.Quantity + warnings: [] + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: + - details: Required if totalAmount is not specified + field: LineItems.SubTotal + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: TaxRateRef.EffectiveTaxRate + warnings: [] + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: TaxRateRef.Name + warnings: [] + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: Required if subTotal is not specified + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + required: false + type: Array + validation: + information: + - details: is not supported and will be ignored + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line is supported + field: LineItems + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: Note + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: false + type: DateTime + validation: + information: + - details: is not supported and will be ignored + field: Allocation.AllocatedOnDate + warnings: [] + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: Allocation.Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: Allocation.CurrencyRate + warnings: [] + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: Allocation.TotalAmount + warnings: [] + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: AccountRef.Name + warnings: [] + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: is not supported and will be ignored + field: Payment.Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: Payment.CurrencyRate + warnings: [] + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: false + type: DateTime + validation: + information: + - details: is not supported and will be ignored + field: Payment.PaidOnDate + warnings: [] + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: Payment.TotalAmount + warnings: [] + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line is supported + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: SubTotal + warnings: [] + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: TaxAmount + warnings: [] + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: is not supported and will be ignored + field: TotalAmount + warnings: [] + required: true + type: Object + FreeAgent: + value: + description: "" + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will be ignored on push. " + field: ContactRef.DataType + id: + description: The reference identifier for the record + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will be ignored on push. " + field: ContactRef.Id + required: false + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: CurrencyRate + id: + description: The identifier for the direct transaction, unique to the company + displayName: Unique Direct Transaction ID + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: Id + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: must be provided + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: must be provided + field: AccountRef.Id + warnings: [] + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: AccountRef.Name + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: "If a Note is provided, this field will be ignored on push. " + field: LineItems.Description + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.EffectiveTaxRate + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.Id + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.Name + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: LineItems.UnitAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Exactly one line item must be specified + field: LineItems + modifiedDate: + description: The date the record was last updated in the system cache + displayName: Modified Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: ModifiedDate + note: + description: The note attached to the direct transaction + displayName: Note + required: true + type: String + validation: + information: + - details: must be provided + field: Note + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: false + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: false + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + required: false + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: must be provided + field: AccountRef.Id + warnings: [] + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: AccountRef.Name + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: false + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: false + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: false + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: false + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: false + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + required: true + type: Object + required: true + type: Array + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will not be mapped. " + field: Reference + sourceModifiedDate: + description: The date the record was last changed in the originating system + displayName: Source Modified Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: SourceModifiedDate + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: false + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: false + type: Number + required: true + type: Object + Oracle NetSuite: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should not be a bank account + field: LineItems.AccountRef + - details: Should only be specified when pushing an expense + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should only be specified when pushing an item (not an expense) + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should be specified when item type is not 'Discount' + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: + - details: Should have the same sign across all line items + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account of type 'Bank' OR type 'Credit Card' + field: AccountRef.Id + required: true + type: Object + required: true + type: Object + required: true + type: Array + validation: + information: + - details: Must contain a single allocation + field: PaymentAllocations + warnings: [] + required: true + type: Object + QuickBooks Desktop: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + required: false + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency + field: Currency + warnings: + - details: Must be a three letter ISO code + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + modifiedDate: + description: The date the record was last updated in the system cache + displayName: Modified Date + required: false + type: DateTime + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4096 characters. + field: Note + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + required: true + type: Object + validation: + information: + - details: The account in which to make the deposit + field: Payment.AccountRef + warnings: [] + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: false + type: String + validation: + information: + - details: Use to reference the check number of this deposit. + field: Payment.Reference + warnings: [] + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain a single payment allocation + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Represents the check number + field: Reference + sourceModifiedDate: + description: The date the record was last changed in the originating system + displayName: Source Modified Date + required: false + type: DateTime + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: true + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: false + type: Number + required: true + type: Object + QuickBooks Online: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: Suppliers + required: false + type: String + value: Suppliers + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must be an Expense or Income account + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be set if ItemRef is not + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be set if AccountRef is not + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be specified on all line items or none. If specified will override QBO tax calculations. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: [] + required: false + type: Object + validation: + information: [] + warnings: + - details: Required for all companies except QuickBooks Online France companies. + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid Id + field: TrackingCategoryRefs.TrackingCategoryRefs + required: false + type: Array + validation: + information: [] + warnings: + - details: Only one tracking category of type CLASS can be provided per item. + field: LineItems.TrackingCategoryRefs + - details: Only one tracking category of type DEPARTMENT can be provided per invoice. + field: LineItems.TrackingCategoryRefs + - details: All DEPARTMENT tracking categories must be the same + field: LineItems.TrackingCategoryRefs + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the Currency of the company + field: Allocation.Currency + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line items + field: Allocation.TotalAmount + required: false + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be Bank, Cash or Asset account + field: AccountRef.Id + warnings: [] + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the Currency of the company + field: Payment.Currency + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line items + field: Payment.TotalAmount + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Must have exactly one payment allocation. + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 22 characters. + field: Reference + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: Suppliers + required: false + type: String + value: Suppliers + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must be an Expense or Income account + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be set if ItemRef is not + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be set if AccountRef is not + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be specified on all line items or none. If specified will override QBO tax calculations. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: [] + required: false + type: Object + validation: + information: [] + warnings: + - details: Required for all companies except QuickBooks Online France companies. + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid Id + field: TrackingCategoryRefs.TrackingCategoryRefs + required: false + type: Array + validation: + information: [] + warnings: + - details: Only one tracking category of type CLASS can be provided per item. + field: LineItems.TrackingCategoryRefs + - details: Only one tracking category of type DEPARTMENT can be provided per invoice. + field: LineItems.TrackingCategoryRefs + - details: All DEPARTMENT tracking categories must be the same + field: LineItems.TrackingCategoryRefs + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the Currency of the company + field: Allocation.Currency + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line items + field: Allocation.TotalAmount + required: false + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be Bank, Cash or Asset account + field: AccountRef.Id + warnings: [] + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the Currency of the company + field: Payment.Currency + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line items + field: Payment.TotalAmount + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Must have exactly one payment allocation. + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 22 characters. + field: Reference + required: true + type: Object + Sage 50 (UK): + value: + description: Direct Cost + displayName: Direct Cost + properties: + accountRef: + description: The bank account to pay this direct cost from. + displayName: Bank Account + properties: + id: + description: Nominal code of the bank account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account and have a max length of 8 characters. + field: accountRef.id + required: true + type: Object + currency: + description: The currency in which the direct cost is issued in. + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: This must match the target account's default currency. + field: currency + currencyRate: + description: The currency rate associated with this transaction. + displayName: Currency Rate + required: true + type: Number + issueDate: + description: The date this payment was issued. + displayName: Issue Date + required: true + type: Number + lineItems: + description: Line items of the direct cost. + displayName: Line Items + properties: + accountRef: + description: Target bank account for the direct cost line item. + displayName: Nominal Code + properties: + id: + description: The ID of the Account the line is linked to. + displayName: Id + required: true + type: String + required: true + type: Object + description: + description: Description of the direct cost line item. + displayName: description + required: false + type: String + quantity: + description: Quantity for the direct cost line item. + displayName: Quantity + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be 1 or -1. + field: LineItems.quantity + subTotal: + description: Amount for the direct cost line item. Debit entries are considered positive, and credit entries are considered negative. + displayName: Net Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot have both subtotal and tax amount as 0 for line item. + field: LineItems.subTotal + taxAmount: + description: Tax amount for the direct cost line item. + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Cannot have both tax amount and subtotal as 0 for line item. + field: LineItems.taxAmount + taxCode: + description: The tax code ID associated with this transaction. + displayName: Tax Code Id + required: true + type: Number + totalAmount: + description: Total amount for the direct cost line item. + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: Will be auto populated using tax amount and net amount. + field: LineItems.totalAmount + warnings: [] + trackingCategoryRefs: + description: Tracking categories associated with this transaction. + displayName: Tracking Category References + properties: + id: + description: The ID of the tracking category associated with the transaction + displayName: Id + required: true + type: String + validation: + information: [] + warnings: + - details: A department is required. If a project reference is provided, the cost code for that project must also be provided. + field: id + required: true + type: Object + unitAmount: + description: Unit amount for the direct cost line item. + displayName: Unit Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot equal 0 and will be set to Net amount if not provided accordingly. + field: LineItems.unitAmount + required: true + type: Array + reference: + description: The user reference for this direct cost. + displayName: Reference + required: false + type: String + subTotal: + description: The net amount being paid in this direct cost. + displayName: Sub Total + required: true + type: Number + validation: + information: + - details: This must equal the sum of the line net amounts + warnings: [] + taxAmount: + description: The tax amount being paid in this direct cost. + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: This must equal the sum of the line tax amounts + warnings: [] + totalAmount: + description: The total amount being paid in this direct cost. + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: This must equal the sum of the line amounts + warnings: [] + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Intacct: + value: + description: Direct Cost + displayName: Direct Cost + properties: + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: When supplying a currency ensure that it exists in your Sage Intacct entity otherwise the request will fail. + field: Currency + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: + - details: Must not contain no more than 1000 characters. + field: LineItems.Description + warnings: [] + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be an existing tax rate in Sage Intacct. + field: TaxRateRef.Id + warnings: [] + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: false + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: false + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: + - details: Must contain at least one line item. + field: LineItems + warnings: [] + note: + description: The note attached to the direct transaction + displayName: Note + required: true + type: String + validation: + information: + - details: Must be used to provide payee's name and contain no more than 80 characters. + field: Note + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If provided, must match the sum of the line items. + field: Allocation.TotalAmount + warnings: [] + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If provided, must match the sum of the line items. + field: Payment.TotalAmount + warnings: [] + required: true + type: Object + required: true + type: Array + validation: + information: + - details: Must contain a single allocation. + field: PaymentAllocations + warnings: [] + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not contain no more than 45 characters. + field: Reference + warnings: [] + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If provided, must match the sum of the line items. + field: TotalAmount + warnings: [] + required: true + type: Object + Sandbox: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + invoiceTo: + description: The entity the record should be invoiced to + displayName: Invoice To + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Array + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: The note attached to the direct transaction + displayName: Note + required: true + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: true + type: String + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: true + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Xero: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: ContactRef.Id + warnings: + - details: Must be a valid GUID. + field: ContactRef.Id + - details: Must match the ID of an existing contact. + field: ContactRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: ContactRef + warnings: [] + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must not be longer than 4000 characters long. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: + - details: If not provided, will be set to the default tax rate for the line's account. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: When one line is negative, all lines must be negative. + field: LineItems.TotalAmount + warnings: + - details: When negative, the push item will be converted to a DirectIncome and will be pushed accordingly. + field: LineItems.TotalAmount + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Allocation.TotalAmount + warnings: + - details: Must be equal to the sum of line items. + field: Allocation.TotalAmount + required: true + type: Object + validation: + information: + - details: Must be provided. + field: PaymentAllocations.Allocation + warnings: [] + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a bank account. + field: AccountRef.Id + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: Payment.AccountRef + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: PaymentAllocations.Payment + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: PaymentAllocations + warnings: [] + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not exceed 255 characters. + field: Reference + warnings: [] + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TaxAmount + warnings: [] + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: [] + required: true + type: Object + validation: + information: [] + warnings: + - details: When negative, the push item will be converted to a DirectIncome and will be pushed accordingly. + Zoho Books: + value: + description: Direct Cost + displayName: Direct Cost + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: false + type: String + required: false + type: Object + validation: + information: + - details: Required when pushing a negative direct cost & should reference either a Customer or Supplier when provided + field: ContactRef + warnings: [] + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: Is required when pushing a negative direct cost + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: + - details: Should be provided when TotalAmount is not provided + field: LineItems.SubTotal + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: Should be provided when SubTotal is not provided + field: LineItems.TotalAmount + warnings: [] + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + required: false + type: Array + required: true + type: Array + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: Is required when pushing a negative direct cost + field: Allocation.Currency + warnings: [] + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: Is required when pushing a negative direct cost + field: Payment.Currency + warnings: [] + required: true + type: Object + required: true + type: Array + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create direct cost model + tags: + - Direct costs + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/directIncomes": + get: + description: |- + Get create direct income model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=directIncomes) for integrations that support creating direct incomes. + operationId: get-create-directIncomes-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + description: Direct Income + displayName: Direct Income + properties: + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must be the same as the PaymentAllocation.Payment.AccountRef.Id currency + field: Currency + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be provided if LineItems.TotalAmount is not provided + field: LineItems.SubTotal + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be provided if LineItems.SubTotal is not provided + field: LineItems.TotalAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line is supported + field: LineItems + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be a Bank Account ID + field: AccountRef.Id + warnings: [] + required: true + type: Object + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line is supported + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: true + type: String + validation: + information: [] + warnings: + - details: Must not exceed 20 characters + field: Reference + required: true + type: Object + FreeAgent: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will be ignored on push. " + field: ContactRef.DataType + id: + description: The reference identifier for the record + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will be ignored on push. " + field: ContactRef.Id + required: false + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: CurrencyRate + id: + description: The identifier for the direct transaction, unique to the company + displayName: Unique Direct Transaction ID + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: Id + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: must be provided + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: must be provided + field: AccountRef.Id + warnings: [] + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: AccountRef.Name + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: "If a Note is provided, this field will be ignored on push. " + field: LineItems.Description + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.EffectiveTaxRate + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.Id + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: TaxRateRef.Name + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: LineItems.UnitAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: Exactly one line item must be specified + field: LineItems + modifiedDate: + description: The date the record was last updated in the system cache + displayName: Modified Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: ModifiedDate + note: + description: The note attached to the direct transaction + displayName: Note + required: true + type: String + validation: + information: + - details: must be provided + field: Note + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: false + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: false + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: false + type: Number + required: false + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: must be provided + field: AccountRef.Id + warnings: [] + name: + description: Name of the account + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: AccountRef.Name + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: false + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: false + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: false + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: false + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: false + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: false + type: Number + required: true + type: Object + required: true + type: Array + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: "is not supported by FreeAgent and will not be mapped. " + field: Reference + sourceModifiedDate: + description: The date the record was last changed in the originating system + displayName: Source Modified Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: "will be ignored on push. " + field: SourceModifiedDate + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: false + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: false + type: Number + required: true + type: Object + Oracle NetSuite: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: + - details: Should have the same sign across all line items + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account of type 'Bank' + field: AccountRef.Id + required: true + type: Object + required: true + type: Object + required: true + type: Array + validation: + information: + - details: Must contain a single allocation + field: PaymentAllocations + warnings: [] + required: true + type: Object + QuickBooks Desktop: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + required: false + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency + field: Currency + warnings: + - details: Must be a three letter ISO code + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + id: + description: The identifier for the direct transaction, unique to the company + displayName: Unique Direct Transaction ID + required: true + type: String + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + required: true + type: Array + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain a single line item + field: LineItems + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 100 characters. + field: Note + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + required: true + type: Object + validation: + information: + - details: The account in which to make the deposit + field: Payment.AccountRef + warnings: [] + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: false + type: String + validation: + information: + - details: Use to reference the check number of this deposit. + field: Payment.Reference + warnings: [] + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain a single payment allocation + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Represents the check number + field: Reference + sourceModifiedDate: + description: The date the record was last changed in the originating system + displayName: Source Modified Date + required: false + type: DateTime + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: Customers + required: false + type: String + value: Customers + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be a Customer reference + field: ContactRef + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 4000 characters. + field: LineItems.Description + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + validation: + information: + - details: Must equal the Quantity multiplied by the UnitAmount. + field: LineItems.SubTotal + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: For UK companies, if a value of NON is provided on all lines the directIncomes will be set to have No VAT. + field: TaxRateRef.Id + - details: If an organisation has Automated Sales Tax enabled for US locales, then 'TAX' (Automated Sales Tax), 'NON' (no tax) or a custom tax rate can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: + - details: For UK companies, cannot have a mix of NON and valid tax rate IDs. + field: TaxRateRef.Id + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + validation: + information: [] + warnings: + - details: All DEPARTMENT tracking categories must be the same + field: LineItems.TrackingCategoryRefs + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Required for refunds + field: AccountRef.Id + - details: Must be Bank or Asset account + field: AccountRef.Id + warnings: [] + required: false + type: Object + required: true + type: Object + required: true + type: Array + validation: + information: [] + warnings: + - details: Must have exactly one payment allocation. + field: PaymentAllocations + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Must be less than 22 characters. + field: Reference + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Tax will not be overridden if TaxAmount is 0. + field: TaxAmount + warnings: [] + required: true + type: Object + validation: + information: + - details: Automated Sales Tax is disabled for this company. + warnings: [] + Sage Intacct: + value: + description: Direct Income + displayName: Direct Income + properties: + currency: + description: The currency of the direct transaction + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: When supplying a currency ensure that it exists in your Sage Intacct entity otherwise the request will fail. + field: Currency + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be used to provide an account id not linked to a bank account. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: + - details: Must not contain more than 1000 characters. + field: LineItems.Description + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: + - details: Must be an existing tax rate in Sage Intacct. + field: TaxRateRef.Id + warnings: [] + required: false + type: Object + validation: + information: + - details: It is only required for VAT enabled transactions. + field: LineItems.TaxRateRef + warnings: [] + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: false + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: false + type: String + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: + - details: Must contain at least one line item. + field: LineItems + warnings: [] + note: + description: The note attached to the direct transaction + displayName: Note + required: false + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be used to provide bank account id. + field: Payment.AccountRef + warnings: [] + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + required: true + type: Object + required: true + type: Array + validation: + information: + - details: Must contain a single payment allocation. + field: PaymentAllocations + warnings: [] + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: true + type: String + validation: + information: + - details: Must be used to provide payee's name and contain no more than 80 characters. + field: Reference + warnings: [] + required: true + type: Object + Sandbox: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: The note attached to the direct transaction + displayName: Note + required: true + type: String + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: true + type: String + subTotal: + description: The total amount of the direct transaction excluding any taxes + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: true + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Xero: + value: + description: Direct Income + displayName: Direct Income + properties: + contactRef: + description: The contact associated with the direct transaction, if known + displayName: Contact Ref + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: ContactRef.Id + warnings: + - details: Must be a valid GUID. + field: ContactRef.Id + - details: Must match the ID of an existing contact. + field: ContactRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: ContactRef + warnings: [] + currency: + description: The currency of the direct transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the direct transaction and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + issueDate: + description: The date the direct transaction was issued + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the direct transaction + displayName: Direct Transaction Lines + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must not be longer than 4000 characters long. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: When one line is negative, all lines must be negative. + field: LineItems.TotalAmount + warnings: + - details: When negative, the push item will be converted to a DirectCost and will be pushed accordingly. + field: LineItems.TotalAmount + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + paymentAllocations: + description: A collection of payments allocated to the direct transaction + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Allocation.TotalAmount + warnings: + - details: Must be equal to the sum of line items. + field: Allocation.TotalAmount + required: true + type: Object + validation: + information: + - details: Must be provided. + field: PaymentAllocations.Allocation + warnings: [] + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a bank account. + field: AccountRef.Id + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: Payment.AccountRef + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: PaymentAllocations.Payment + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: PaymentAllocations + warnings: [] + reference: + description: User friendly reference for the direct transaction + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not exceed 255 characters. + field: Reference + warnings: [] + taxAmount: + description: The total amount of tax on the direct transaction + displayName: Tax Amount + required: false + type: Number + totalAmount: + description: The amount of the direct transaction, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: [] + required: true + type: Object + validation: + information: [] + warnings: + - details: When negative, the push item will be converted to a DirectCost and will be pushed accordingly. + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create direct income model + tags: + - Direct incomes + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/invoices": + get: + description: |- + Get create/update invoice model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=invoices) for integrations that support creating and updating invoices. + operationId: get-create-update-invoices-model + responses: + "200": + content: + application/json: + examples: + FreeAgent: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + options: + - displayName: AED + required: false + type: String + value: AED + - displayName: AMD + required: false + type: String + value: AMD + - displayName: AOA + required: false + type: String + value: AOA + - displayName: ARS + required: false + type: String + value: ARS + - displayName: AUD + required: false + type: String + value: AUD + - displayName: AWG + required: false + type: String + value: AWG + - displayName: AZN + required: false + type: String + value: AZN + - displayName: BBD + required: false + type: String + value: BBD + - displayName: BDT + required: false + type: String + value: BDT + - displayName: BGN + required: false + type: String + value: BGN + - displayName: BRL + required: false + type: String + value: BRL + - displayName: BWP + required: false + type: String + value: BWP + - displayName: CAD + required: false + type: String + value: CAD + - displayName: CHF + required: false + type: String + value: CHF + - displayName: CLP + required: false + type: String + value: CLP + - displayName: CNY + required: false + type: String + value: CNY + - displayName: COP + required: false + type: String + value: COP + - displayName: CRC + required: false + type: String + value: CRC + - displayName: CUC + required: false + type: String + value: CUC + - displayName: CUP + required: false + type: String + value: CUP + - displayName: CZK + required: false + type: String + value: CZK + - displayName: DKK + required: false + type: String + value: DKK + - displayName: DOP + required: false + type: String + value: DOP + - displayName: EGP + required: false + type: String + value: EGP + - displayName: EUR + required: false + type: String + value: EUR + - displayName: FJD + required: false + type: String + value: FJD + - displayName: GBP + required: false + type: String + value: GBP + - displayName: GEL + required: false + type: String + value: GEL + - displayName: GHS + required: false + type: String + value: GHS + - displayName: GTQ + required: false + type: String + value: GTQ + - displayName: GYD + required: false + type: String + value: GYD + - displayName: HKD + required: false + type: String + value: HKD + - displayName: HNL + required: false + type: String + value: HNL + - displayName: HRK + required: false + type: String + value: HRK + - displayName: HUF + required: false + type: String + value: HUF + - displayName: IDR + required: false + type: String + value: IDR + - displayName: ILS + required: false + type: String + value: ILS + - displayName: INR + required: false + type: String + value: INR + - displayName: ISK + required: false + type: String + value: ISK + - displayName: JMD + required: false + type: String + value: JMD + - displayName: JPY + required: false + type: String + value: JPY + - displayName: KES + required: false + type: String + value: KES + - displayName: KRW + required: false + type: String + value: KRW + - displayName: KWD + required: false + type: String + value: KWD + - displayName: KYD + required: false + type: String + value: KYD + - displayName: KZT + required: false + type: String + value: KZT + - displayName: LAK + required: false + type: String + value: LAK + - displayName: LBP + required: false + type: String + value: LBP + - displayName: LKR + required: false + type: String + value: LKR + - displayName: LTL + required: false + type: String + value: LTL + - displayName: LVL + required: false + type: String + value: LVL + - displayName: MAD + required: false + type: String + value: MAD + - displayName: MDL + required: false + type: String + value: MDL + - displayName: MGA + required: false + type: String + value: MGA + - displayName: MUR + required: false + type: String + value: MUR + - displayName: MVR + required: false + type: String + value: MVR + - displayName: MWK + required: false + type: String + value: MWK + - displayName: MXN + required: false + type: String + value: MXN + - displayName: MYR + required: false + type: String + value: MYR + - displayName: MZN + required: false + type: String + value: MZN + - displayName: NAD + required: false + type: String + value: NAD + - displayName: NGN + required: false + type: String + value: NGN + - displayName: NOK + required: false + type: String + value: NOK + - displayName: NPR + required: false + type: String + value: NPR + - displayName: NZD + required: false + type: String + value: NZD + - displayName: OMR + required: false + type: String + value: OMR + - displayName: PEN + required: false + type: String + value: PEN + - displayName: PHP + required: false + type: String + value: PHP + - displayName: PKR + required: false + type: String + value: PKR + - displayName: PLN + required: false + type: String + value: PLN + - displayName: QAR + required: false + type: String + value: QAR + - displayName: RON + required: false + type: String + value: RON + - displayName: RSD + required: false + type: String + value: RSD + - displayName: RUB + required: false + type: String + value: RUB + - displayName: RWF + required: false + type: String + value: RWF + - displayName: SAR + required: false + type: String + value: SAR + - displayName: SCR + required: false + type: String + value: SCR + - displayName: SEK + required: false + type: String + value: SEK + - displayName: SGD + required: false + type: String + value: SGD + - displayName: THB + required: false + type: String + value: THB + - displayName: TND + required: false + type: String + value: TND + - displayName: TRY + required: false + type: String + value: TRY + - displayName: TTD + required: false + type: String + value: TTD + - displayName: TWD + required: false + type: String + value: TWD + - displayName: TZS + required: false + type: String + value: TZS + - displayName: UAH + required: false + type: String + value: UAH + - displayName: UGX + required: false + type: String + value: UGX + - displayName: USD + required: false + type: String + value: USD + - displayName: UYU + required: false + type: String + value: UYU + - displayName: VEF + required: false + type: String + value: VEF + - displayName: VND + required: false + type: String + value: VND + - displayName: VUV + required: false + type: String + value: VUV + - displayName: XAF + required: false + type: String + value: XAF + - displayName: XCD + required: false + type: String + value: XCD + - displayName: XOF + required: false + type: String + value: XOF + - displayName: ZAR + required: false + type: String + value: ZAR + - displayName: ZMK + required: false + type: String + value: ZMK + required: false + type: String + validation: + information: + - details: If not specified, defaults to the company's native currency + field: Currency + warnings: [] + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: false + type: DateTime + validation: + information: + - details: If not specified, payment terms will default to 0 days (due on receipt) + field: DueDate + warnings: [] + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: The FreeAgent income category + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: false + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + required: true + type: Array + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + required: true + type: Object + FreshBooks: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: false + type: String + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be valid Customer Id + field: CustomerRef.Id + required: true + type: Object + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: false + type: DateTime + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: false + type: String + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: false + type: Array + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Draft + required: false + type: Array + value: Draft + - displayName: Open + required: false + type: Array + value: Submitted + required: true + type: String + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + additionalTaxAmount: + description: Tax added to the total tax of the lines + displayName: Additional Tax Amount + required: false + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: AdditionalTaxAmount + warnings: [] + amountDue: + description: The amount outstanding on the invoice + displayName: Amount Due + required: false + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: AmountDue + - details: Must be at least zero and no more than that the total amount. + field: AmountDue + warnings: [] + currency: + description: Currency of the invoice + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: CustomerRef + warnings: [] + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: false + type: String + validation: + information: + - details: Must not be greater than 8 characters long. + field: InvoiceNumber + warnings: [] + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must not be before the due date. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: + - details: Must not be greater than 225 characters long. + field: LineItems.Description + warnings: [] + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: ItemRef.Id + warnings: [] + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.SubTotal + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Precision must be maximum of two decimal places. + field: LineItems.TaxAmount + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: [] + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.TaxRateRef + warnings: [] + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: LineItems.TotalAmount + - details: Must be provided. + field: LineItems.TotalAmount + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: LineItems.UnitAmount + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + subTotal: + description: The total amount of the invoice excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: SubTotal + warnings: [] + totalAmount: + description: The amount of the invoice, inclusive of tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Must be greater than zero. + field: TotalAmount + totalDiscount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: TotalDiscount + warnings: [] + totalTaxAmount: + description: The total amount of tax on the invoice + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: TotalTaxAmount + warnings: [] + required: true + type: Object + Oracle NetSuite: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: false + type: String + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: false + type: DateTime + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.Quantity + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be provided if and only if item does not have type 'Discount' + field: LineItems.SubTotal + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: false + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if item does not have type 'Discount' + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: A single location tracking category must be present on all LineItems. Optionally, a single classification tracking category may be present on all LineItems. Also optionally, a single department tracking category may be present on all LineItems. + field: TrackingCategoryRefs.Id + warnings: [] + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must not be provided for 'Discount' type items + field: LineItems.UnitAmount + required: true + type: Array + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the customer + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the customer + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: false + type: DateTime + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 11 characters. + field: InvoiceNumber + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: LineItems.Description + discountAmount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Can only be set if the line items itemRef refers to an item of type discount + field: LineItems.DiscountAmount + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + validation: + information: [] + warnings: + - details: Can only be set if the line items itemRef refers to an item of type discount + field: LineItems.DiscountPercentage + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.ItemRef + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: For US versions of QuickBooks Desktop, this must be a Tax Code + field: TaxRateRef.Id + - details: For US versions of QuickBooks Desktop, this can only be set when Sales Tax is enabled; must be either 'Tax' or 'Non' + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Note about the invoice + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: Note + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + subTotal: + description: The total amount of the invoice excluding any taxes + displayName: Sub Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of sub totals in the line items. + field: SubTotal + totalAmount: + description: The amount of the invoice, inclusive of tax + displayName: Total Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of total amounts in the line items. + field: TotalAmount + totalTaxAmount: + description: The total amount of tax on the invoice + displayName: Tax Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of tax amounts in the line items. + field: TotalTaxAmount + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: + - details: Must not be less than 0. + field: CurrencyRate + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + validation: + information: [] + warnings: + - details: If provided must be a number between 0 and 100. + field: DiscountPercentage + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Maximum character length should not be longer than 4000. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: + - details: When set to SHIPPING_ITEM_ID, the item will represent shipping. + field: ItemRef.Id + - details: If not provided, will use the default item set for the company. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: false + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: false + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then 'TAX' (Automated Sales Tax), 'NON' (no tax) or a custom tax rate can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: A tracking category of type CLASS can only be provided if ClassTrackingPerTxnLine is enabled for the QBO company. + field: TrackingCategoryRefs.Id + - details: Only one tracking category of type CLASS can be provided per item. + field: TrackingCategoryRefs.Id + - details: A tracking category of type DEPARTMENT should be declared at the top level item (first line item). + field: TrackingCategoryRefs.Id + - details: A tracking category of type DEPARTMENT can only be provided if TrackDepartments is enabled for the QBO company. + field: TrackingCategoryRefs.Id + - details: Only one tracking category of type DEPARTMENT can be provided per invoice. + field: TrackingCategoryRefs.Id + - details: Must match the ID of an existing tracking category and be of type DEPARTMENT or CLASS. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + validation: + information: + - details: QuickBooks Online only supports "Submitted" as a status for new invoices. + field: Status + warnings: [] + totalDiscount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + totalTaxAmount: + description: The total amount of tax on the invoice + displayName: Tax Amount + required: false + type: Number + validation: + information: + - details: Tax will not be overridden if TotalTaxAmount is 0. + field: TotalTaxAmount + warnings: [] + required: true + type: Object + validation: + information: + - details: Automated Sales Tax is disabled for this company. + warnings: [] + Sage 50 (UK): + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: The currency in which the invoice is issued in. + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: This must match the customer's default currency. + field: currency + customerRef: + description: Customer to be invoiced. + displayName: Customer + properties: + id: + description: Identifier of the customer. + displayName: Customer Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer and have a max length of 8 characters. + field: customerRef.id + required: true + type: Object + invoiceNumber: + description: The reference number for this invoice + displayName: Invoice Number + required: true + type: String + lineItems: + description: Line items of the invoice. + displayName: Line Items + properties: + accountRef: + description: Identifier for the account. + displayName: Account Reference + properties: + id: + description: Identifier of the account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. The account must also not be a bank account + field: accountRef.id + required: true + type: Object + taxRateRef: + description: Tax rate reference of a invoice line item. + displayName: Tax Rate Reference + properties: + id: + description: ID of the tax rate. + displayName: Tax Rate Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: taxRateRef.id + required: true + type: Object + trackingCategoryRefs: + description: Tracking categories for the line item + displayName: Tracking Categories + properties: + id: + description: Prefixed identifier for tracking category e.g. project_{x}, department_{x} + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Projects assigned with project_{x} must exist in Sage50 + field: trackingCategoryRefs.id + - details: Departments assigned with department_{x} must exist in Sage50 + field: trackingCategoryRefs.id + required: false + type: Array + required: true + type: Array + note: + description: To be used for any additional information associated with the invoice. + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Maximum 60 characters + field: note + status: + description: The status of the invoice + displayName: Status + options: + - displayName: Submitted + required: false + type: String + value: Submitted + required: false + type: String + validation: + information: + - details: If this is not set, it will default to 'Submitted'. + field: status + warnings: [] + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: false + type: String + validation: + information: + - details: If supplied, must match the currency of the customer. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must be provided. + field: LineItems.Description + warnings: + - details: Should not be longer than 2000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: false + type: Number + validation: + information: + - details: If supplied, must match the total of the line including tax. + field: LineItems.TotalAmount + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + required: false + type: String + required: true + type: Object + Sage Intacct: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must not be set when creating a sales invoice. + field: AccountRef.Id + - details: Must be set when creating an invoice. + field: AccountRef.Id + warnings: [] + required: true + type: Object + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be set for all line items when creating a sales invoice otherwise this field must be empty. + field: ItemRef.Id + warnings: [] + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be greater than 0 for a sales invoice. + field: LineItems.Quantity + - details: Must be set to 1 for an invoice. + field: LineItems.Quantity + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must not be set for a sales invoice. + field: TaxRateRef.Id + - details: Must be set for an invoice. + field: TaxRateRef.Id + warnings: [] + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Is optional when creating an invoice. + field: TrackingCategoryRefs.Id + - details: When creating a sales invoice WAREHOUSE must be supplied. + field: TrackingCategoryRefs.Id + - details: When creating a sales invoice the ITEM category id must match the ItemRef.Id. + field: TrackingCategoryRefs.Id + - details: Available tracking categories DEPARTMENT, LOCATION, CLASS, ITEM, PROJECT, WAREHOUSE, TASK, CONTRACT, CUSTOMER, SUPPLIER. + field: TrackingCategoryRefs.Id + - details: Must take the form 'TrackingCategoryName-XYZ' e.g. to track an item with id 123 the id must be ITEM-123 + field: TrackingCategoryRefs.Id + warnings: [] + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be greater than zero. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must contain at least one line item. + field: LineItems + warnings: [] + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + required: true + type: String + validation: + information: + - details: Must be either Draftor Submitted. + field: Status + warnings: [] + required: true + type: Object + Sandbox: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + additionalTaxAmount: + description: Tax added to the total tax of the lines + displayName: Additional Tax Amount + required: true + type: Number + additionalTaxPercentage: + description: The percentage of the additional tax to the TotalAmount + displayName: Additional Tax Percentage + required: true + type: Number + amountDue: + description: The amount outstanding on the invoice + displayName: Amount Due + required: true + type: Number + currency: + description: Currency of the invoice + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: true + type: String + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + discountAmount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: true + type: Number + isDirectIncome: + description: True if this invoice is also mapped as a direct income + displayName: Is Direct Income + required: true + type: Boolean + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + subTotal: + description: The amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total Amount + required: true + type: Number + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + tracking: + description: A collection of items this line item is being tracked against + displayName: Accounts Receivable Tracking + properties: + categoryRefs: + description: A collection of categories this line item is being tracked against + displayName: Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + customerRef: + description: Reference to the customer this line item is being tracked against + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + isBilledTo: + description: The type of item this line item is billed to. + displayName: Is Billed To + required: true + type: String + isRebilledTo: + description: The type of item this line item is billed to + displayName: Is Rebilled To + required: true + type: String + projectRef: + description: Reference to the project this line item is being tracked against + displayName: Project Reference + properties: + id: + description: The reference identifier for the Project + displayName: Identifier + required: true + type: String + name: + description: The name of the Project referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Note about the invoice + displayName: Note + required: true + type: String + paidOnDate: + description: The date that the invoice was fully paid + displayName: Paid On Date + required: true + type: DateTime + paymentAllocations: + description: A collection of payments allocated to the invoice + displayName: Payment Allocations + properties: + allocation: + description: The allocation information + displayName: Allocation + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + currency: + description: The currency of the transaction + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the transaction + displayName: Currency Exchange Rate + required: true + type: Number + totalAmount: + description: The total amount that has been allocated + displayName: Total Amount + required: true + type: Number + required: true + type: Object + payment: + description: The payment to be allocated + displayName: Payment + properties: + accountRef: + description: Reference to the account associated with the allocated payment + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the allocated payment and the currency of the base company + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the allocated payment + displayName: Identifier + required: true + type: String + note: + description: Any additional text based information associated with the allocated payment + displayName: Note + required: true + type: String + paidOnDate: + description: The date the payment was paid + displayName: Paid On Date + required: true + type: DateTime + reference: + description: Reference associated with the allocated payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount that has been paid + displayName: Total Amount + required: true + type: Number + required: true + type: Object + required: true + type: Array + salesOrderRefs: + description: References to related Sales Orders + displayName: Sales Order References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Array + status: + description: The current state of the invoice + displayName: Invoice Status + required: true + type: String + subTotal: + description: The total amount of the invoice excluding any taxes + displayName: Sub Total Amount + required: true + type: Number + totalAmount: + description: The amount of the invoice, inclusive of tax + displayName: Total Amount + required: true + type: Number + totalDiscount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: true + type: Number + totalTaxAmount: + description: The total amount of tax on the invoice + displayName: Tax Amount + required: true + type: Number + withholdingTax: + description: A collection of tax deductions + displayName: Withholding Tax + properties: + amount: + description: Deduction amount + displayName: Amount + required: true + type: Number + name: + description: Name of the deduction + displayName: Name + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If no rate is specified, the Xero day rate will be applied. + field: CurrencyRate + ref: https://central.xero.com/s/#CurrencySettings$Rates + warnings: [] + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must be a valid GUID. + field: CustomerRef.Id + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: CustomerRef + warnings: [] + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: DueDate + warnings: [] + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: false + type: String + validation: + information: + - details: Must not exceed 255 charaters long. + field: InvoiceNumber + warnings: [] + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: IssueDate + warnings: [] + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: LineItems.AccountRef + warnings: [] + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: true + type: String + validation: + information: + - details: Must not be longer than 4000 characters long. + field: LineItems.Description + warnings: [] + discountPercentage: + description: The percentage rate of any discount that has been applied + displayName: Discount Percentage + required: false + type: Number + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.Quantity + warnings: [] + taxAmount: + description: The amount of tax for the line + displayName: Tax Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.TaxAmount + warnings: [] + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: TaxRateRef.Id + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + trackingCategoryRefs: + description: A collection of categories this item is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must not be a parent tracking category. + field: TrackingCategoryRefs.Id + - details: Must be provided. + field: TrackingCategoryRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + warnings: [] + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: LineItems.UnitAmount + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: LineItems + warnings: [] + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + required: true + type: Object + Zoho Books: + value: + description: An invoice is an itemised record of goods sold or services rendered to a customer + displayName: Invoice + properties: + currency: + description: Currency of the invoice + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the customer's currency + field: Currency + currencyRate: + description: The exchange rate between the currency of the invoice and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: [] + warnings: + - details: Must be greater than or equal to 0 + field: CurrencyRate + customerRef: + description: Reference to the customer the invoice has been sent to + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + dueDate: + description: The date the invoice is due to be paid by + displayName: Due Date + required: true + type: DateTime + invoiceNumber: + description: User friendly reference identifier for the invoice + displayName: Invoice Number + required: false + type: String + issueDate: + description: The issuing date of the invoice + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: A collection of lines that detail items related to the invoice + displayName: Line Items + properties: + accountRef: + description: Reference to the nominal account the line item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be of type 'Income' or 'Other Income' + field: LineItems.AccountRef + description: + description: Friendly name of the goods or services purchased + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must be provided if ItemRef is not set + field: LineItems.Description + discountAmount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + itemRef: + description: Reference to the product or service type, or inventory item, the line item is linked to + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if Description is not set + field: LineItems.ItemRef + quantity: + description: The number of units of goods or services purchased + displayName: Quantity + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than or equal to 0 + field: LineItems.Quantity + taxRateRef: + description: Reference to the tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + unitAmount: + description: The price of each unit of goods or services + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: [] + warnings: + - details: The sum of subtotals over all the line items must be greater than or equal to 0 + field: LineItems + - details: Must not be empty + field: LineItems + note: + description: Note about the invoice + displayName: Note + required: false + type: String + status: + description: The current state of the invoice + displayName: Invoice Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Submitted + required: false + type: String + value: Submitted + - displayName: Void + required: false + type: String + value: Void + required: true + type: String + totalDiscount: + description: The value, in the given invoice currency, of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: If DiscountAmount is set for at least one Line Item, TotalDiscount must be the sum of Discount Amounts over all line items. Otherwise invoice level discount will be applied + field: TotalDiscount + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update invoice model + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/items": + get: + description: |- + Get create item model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=items) for integrations that support creating items. + operationId: get-create-items-model + responses: + "200": + content: + application/json: + examples: + QuickBooks Desktop: + value: + description: An item includes details about a product or service that is provided to customers, or provided by suppliers + displayName: Item + properties: + billItem: + description: Item details specific to its usage with bills + displayName: Bill Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + name: + description: Name of the account + displayName: Name + required: false + type: String + required: false + type: Object + description: + description: The description of the item + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4096 characters. + field: BillItem.Description + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 30 characters. + field: TaxRateRef.Name + required: false + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: false + type: Number + validation: + information: [] + warnings: + - details: Value should be zero or greater + field: BillItem.UnitPrice + required: false + type: Object + invoiceItem: + description: Item details specific to its usage with invoices + displayName: Invoice Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: The description of the item + displayName: Description + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 4096 characters. + field: InvoiceItem.Description + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 30 characters. + field: TaxRateRef.Name + required: false + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: true + type: Number + validation: + information: [] + warnings: + - details: Value should be zero or greater + field: InvoiceItem.UnitPrice + required: true + type: Object + itemStatus: + description: The state of the item + displayName: Item Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + name: + description: The name for the item + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: "Sub-items are supported by introducing a colon in between parent and child i.e. Parent : Child" + field: Name + - details: Max length of 31 characters. + field: Name + type: + description: The type of the item + displayName: Item Type + options: + - displayName: Non inventory type + required: false + type: String + value: NonInventory + - displayName: Service type + required: false + type: String + value: Service + required: true + type: String + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: An item includes details about a product or service that is provided to customers, or provided by suppliers + displayName: Item + properties: + billItem: + description: Item details specific to its usage with bills + displayName: Bill Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: The description of the item + displayName: Description + required: true + type: String + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) or 'NON' (no tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: false + type: Number + required: true + type: Object + code: + description: A user friendly reference for the item + displayName: Code + required: false + type: String + validation: + information: + - details: Should not be longer than 21 characters. + field: Code + warnings: [] + invoiceItem: + description: Item details specific to its usage with invoices + displayName: Invoice Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: The description of the item + displayName: Description + required: true + type: String + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: + - details: If an organisation has Automated Sales Tax enabled for US locales, then only 'TAX' (Automated Sales Tax) or 'NON' (no tax) can be used. If Automated Sales Tax is disabled for US locales then 'TAX' (Automated Sales Tax) or 'NON' (no tax) will not be accepted and a different tax rate must be used. + field: TaxRateRef.Id + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: false + type: Number + required: true + type: Object + isBillItem: + description: State whether this item can be used with bills + displayName: Is Bill Item? + required: true + type: Boolean + isInvoiceItem: + description: State whether this item can be used with invoices + displayName: Is Invoice Item? + required: true + type: Boolean + name: + description: The name for the item + displayName: Name + required: true + type: String + validation: + information: + - details: Should not be longer than 21 characters. + field: Name + warnings: + - details: Names must be unique across items. + field: Name + type: + description: The type of the item + displayName: Item Type + options: + - displayName: Non Inventory + required: false + type: String + value: NonInventory + - displayName: Service + required: false + type: String + value: Service + required: true + type: String + required: true + type: Object + Sandbox: + value: + description: An item includes details about a product or service that is provided to customers, or provided by suppliers + displayName: Item + properties: + billItem: + description: Item details specific to its usage with bills + displayName: Bill Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: The description of the item + displayName: Description + required: true + type: String + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: true + type: Number + required: true + type: Object + code: + description: A user friendly reference for the item + displayName: Code + required: true + type: String + invoiceItem: + description: Item details specific to its usage with invoices + displayName: Invoice Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: The description of the item + displayName: Description + required: true + type: String + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + unitPrice: + description: The default unit price for the item + displayName: Unit Price + required: true + type: Number + required: true + type: Object + isBillItem: + description: State whether this item can be used with bills + displayName: Is Bill Item? + required: true + type: Boolean + isInvoiceItem: + description: State whether this item can be used with invoices + displayName: Is Invoice Item? + required: true + type: Boolean + itemStatus: + description: The state of the item + displayName: Item Status + required: true + type: String + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + name: + description: The name for the item + displayName: Name + required: true + type: String + type: + description: The type of the item + displayName: Item Type + required: true + type: String + required: true + type: Object + Xero: + value: + description: An item includes details about a product or service that is provided to customers, or provided by suppliers + displayName: Item + properties: + billItem: + description: Item details specific to its usage with bills + displayName: Bill Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + validation: + information: [] + warnings: + - details: Must be provided if Item is of type Inventory. + field: AccountRef.Id + - details: Must be provided if AccountRef is not null. + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Must be provided if Item is of type Inventory. + field: BillItem.AccountRef + description: + description: The description of the item + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must not be longer than 4000 characters long. + field: BillItem.Description + taxRateRef: + description: Reference to the default tax rate code the line item is linked to + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be provided if TaxRateRef is not null. + field: TaxRateRef.Id + required: false + type: Object + required: false + type: Object + validation: + information: + - details: Must be provided if Item is of type Inventory. + field: BillItem + - details: Must not be provided if IsBillItem is false. + field: BillItem + - details: Must be provided if IsBillItem is true. + field: BillItem + warnings: [] + code: + description: A user friendly reference for the item + displayName: Code + required: true + type: String + validation: + information: [] + warnings: + - details: Must not be longer than 30 characters long. + field: Code + - details: Must be unique. + field: Code + - details: Must be provided. + field: Code + invoiceItem: + description: Item details specific to its usage with invoices + displayName: Invoice Item Details + properties: + accountRef: + description: Reference to the default nominal account the item is linked to + displayName: Nominal Account Reference + required: false + type: Object + description: + description: The description of the item + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must not be longer than 4000 characters long. + field: InvoiceItem.Description + required: false + type: Object + validation: + information: + - details: Must not be provided if IsInvoiceItem is false. + field: InvoiceItem + - details: Must be provided if IsInvoiceItem is true. + field: InvoiceItem + warnings: [] + itemStatus: + description: The state of the item + displayName: Item Status + required: false + type: String + validation: + information: + - details: Is ignored on push, and ItemStatus is always mapped as "Unknown" + field: ItemStatus + warnings: [] + name: + description: The name for the item + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Must not be longer than 50 characters long. + field: Name + type: + description: The type of the item + displayName: Item Type + required: false + type: String + validation: + information: + - details: Must be 'Unknown' or 'Inventory', otherwise Item.Type will be defaulted to 'Unknown'. + field: Type + warnings: + - details: Cannot be of type Inventory if no Inventory account exists in Xero. + field: Type + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create item model + tags: + - Items + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/journalEntries": + get: + description: |- + Get create journal entry model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=journalEntries) for integrations that support creating journal entries. + operationId: get-create-journalEntries-model + responses: + "200": + content: + application/json: + examples: + Dynamics 365 Business Central: + value: + displayName: JournalEntry + properties: + description: + description: An optional top level description for the journal entry + displayName: Description + required: false + type: String + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + validation: + information: [] + warnings: + - details: Bank accounts are not allowed + field: JournalLines.AccountRef + currency: + description: The currency for the line + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: Only base currency is allowed + field: JournalLines.Currency + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + required: true + type: Array + validation: + information: [] + warnings: + - details: Must contain 2 journal lines + field: JournalLines + journalRef: + description: Reference to the journal in which this journal entry was created + displayName: Journal Reference + properties: + id: + description: The reference identifier for the journal + displayName: Identifier + required: true + type: String + required: true + type: Object + validation: + information: + - details: Only General type Journals are allowed + field: JournalRef + warnings: [] + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + required: true + type: Object + Oracle NetSuite: + value: + displayName: JournalEntry + properties: + description: + description: An optional top level description for the journal entry + displayName: Description + required: false + type: String + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + required: true + type: Object + validation: + information: + - details: Specified account must be in the same base currency as the subsidiary + field: JournalLines.AccountRef + warnings: [] + currency: + description: The currency for the line + displayName: Currency + required: false + type: String + validation: + information: + - details: Must be the base currency + field: JournalLines.Currency + warnings: [] + description: + description: The description for the journal line + displayName: Description + required: false + type: String + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: trackingCategories + required: false + type: String + value: trackingCategories + - displayName: customers + required: false + type: String + value: customers + - displayName: suppliers + required: false + type: String + value: suppliers + required: true + type: String + validation: + information: [] + warnings: + - details: At most one trackingCategory RecordRef of each type (classification/department/location) may be provided, and only one entity (either customers/suppliers) RecordRef may be provided + field: RecordRefs.DataType + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: false + type: Array + required: true + type: Object + required: true + type: Array + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: false + type: DateTime + validation: + information: + - details: Defaults to today's date if not specified + field: PostedOn + warnings: [] + required: true + type: Object + QuickBooks Desktop: + value: + displayName: JournalEntry + properties: + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + required: true + type: Object + validation: + information: [] + warnings: + - details: The currency of all accounts in the Journal Entry must use the base currency of the QuickBooks Desktop company + field: JournalLines.AccountRef + currency: + description: The currency for the line + displayName: Currency + required: false + type: String + validation: + information: + - details: Must match the base currency of the QuickBooks Desktop company + field: JournalLines.Currency + - details: If not set, will default to the default currency of the QuickBooks Desktop company + field: JournalLines.Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the QuickBooks Desktop company + field: JournalLines.Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: JournalLines.Currency + description: + description: The description for the journal line + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: JournalLines.Description + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + validation: + information: + - details: For debit lines, the net amount should be positive, for credit lines it should be negative + field: JournalLines.NetAmount + - details: The sum of net amounts for all line items must be 0 + field: JournalLines.NetAmount + warnings: [] + required: true + type: Array + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: false + type: DateTime + required: true + type: Object + QuickBooks Online: + value: + displayName: JournalEntry + properties: + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + currency: + description: The currency for the line + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company + field: JournalLines.Currency + - details: When present, all JournalLine currencies should match + field: JournalLines.Currency + warnings: [] + description: + description: The description for the journal line + displayName: Description + required: false + type: String + validation: + information: + - details: Must be no longer than 4000 characters long + field: JournalLines.Description + warnings: [] + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + validation: + information: [] + warnings: + - details: Must be 'trackingCategories' + field: RecordRefs.DataType + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must begin with 'CLASS_' or 'DEPARTMENT_' + field: RecordRefs.Id + - details: Must match the ID of an existing tracking category and be of type 'DEPARTMENT' or 'CLASS'. + field: RecordRefs.Id + required: true + type: Array + validation: + information: [] + warnings: + - details: Must not contain multiple 'CLASS_' records or 'DEPARTMENT_' records + field: Tracking.RecordRefs + required: false + type: Object + required: true + type: Array + validation: + information: + - details: There must be at least two lines + field: JournalLines + warnings: [] + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + required: true + type: Object + validation: + information: [] + warnings: + - details: To push a JournalEntry to a French Company in QuickBooks Online, an active JournalCode with type 'Others' or 'Autres' must exist inside the Company + QuickBooks Online Sandbox: + value: + displayName: JournalEntry + properties: + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + currency: + description: The currency for the line + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company + field: JournalLines.Currency + - details: When present, all JournalLine currencies should match + field: JournalLines.Currency + warnings: [] + description: + description: The description for the journal line + displayName: Description + required: false + type: String + validation: + information: + - details: Must be no longer than 4000 characters long + field: JournalLines.Description + warnings: [] + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + validation: + information: [] + warnings: + - details: Must be 'trackingCategories' + field: RecordRefs.DataType + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must begin with 'CLASS_' or 'DEPARTMENT_' + field: RecordRefs.Id + - details: Must match the ID of an existing tracking category and be of type 'DEPARTMENT' or 'CLASS'. + field: RecordRefs.Id + required: true + type: Array + validation: + information: [] + warnings: + - details: Must not contain multiple 'CLASS_' records or 'DEPARTMENT_' records + field: Tracking.RecordRefs + required: false + type: Object + required: true + type: Array + validation: + information: + - details: There must be at least two lines + field: JournalLines + warnings: [] + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + required: true + type: Object + validation: + information: [] + warnings: + - details: To push a JournalEntry to a French Company in QuickBooks Online, an active JournalCode with type 'Others' or 'Autres' must exist inside the Company + Sage 50 (UK): + value: + displayName: JournalEntry + properties: + createdOn: + description: Date on which the journal was created in Sage50. + displayName: Created On + required: false + type: DateTime + validation: + information: + - details: if empty then Sage 50 will auto generate a created on date + field: createdOn + warnings: [] + dataType: + description: Data type of the underlying record that created the journal entry. + displayName: Data Type + required: false + type: String + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: dataType + description: + description: Optional description of the journal entry. + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: description + id: + description: The reference journal id + displayName: Id + required: false + type: String + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: id + journalLines: + description: Journal line items of the journal entry. + displayName: Journal Lines + properties: + accountRef: + description: Links a journal entry to any associated accounts. + displayName: accountRef + properties: + id: + description: The ID of the Account the line is linked to. + displayName: Id + required: false + type: String + validation: + information: [] + warnings: + - details: Cannot post journal entries against non-base currency nominal codes + field: id + required: false + type: Object + currency: + description: Currency for the journal line item. + displayName: currency + required: false + type: String + validation: + information: [] + warnings: + - details: Journal entries can only be pushed in the base currency of the target company. + field: journalLines.currency + description: + description: Description of the journal line item. + displayName: description + required: false + type: String + netAmount: + description: Amount for the journal line. Debit entries are considered positive, and credit entries are considered negative. + displayName: Net Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Cannot equal 0 + field: journalLines.netAmount + required: true + type: Array + journalRef: + description: Links journal entries to the relevant journal + displayName: Journal Reference + required: false + type: Object + modifiedDate: + description: Date on which the record was last updated via pushes. + displayName: Source Modified Date + required: true + type: DateTime + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: modifiedDate + name: + description: The reference journal name + displayName: Name + required: false + type: String + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: name + recordRef: + description: Links a journal entry to the underlying record that created it. + displayName: Record Reference + required: false + type: Object + sourceModifiedDate: + description: Date on which the record was last changed in Sage50. + displayName: Source Modified Date + required: true + type: DateTime + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: sourceModifiedDate + updatedOn: + description: Date on which the journal was last updated in Sage50. + displayName: Updated On + required: true + type: DateTime + validation: + information: [] + warnings: + - details: Is not supported and therefore will be ignored + field: updatedOn + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Intacct: + value: + displayName: JournalEntry + properties: + description: + description: An optional top level description for the journal entry + displayName: Description + required: true + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 512 characters + field: Description + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: true + type: Object + currency: + description: The currency for the line + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: If provided, must match the base currency for the company + field: JournalLines.Currency + description: + description: The description for the journal line + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 512 characters + field: JournalLines.Description + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must not be a 0 amount + field: JournalLines.NetAmount + required: true + type: Array + validation: + information: [] + warnings: + - details: There must be at least two lines + field: JournalLines + journalRef: + description: Reference to the journal in which this journal entry was created + displayName: Journal Reference + properties: + id: + description: The reference identifier for the journal + displayName: Identifier + required: true + type: String + required: true + type: Object + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + required: true + type: Object + Sandbox: + value: + displayName: JournalEntry + properties: + createdOn: + description: The date the entry was created in the originating system + displayName: Created On + required: true + type: DateTime + description: + description: An optional top level description for the journal entry + displayName: Description + required: true + type: String + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: The currency for the line + displayName: Currency + required: true + type: String + description: + description: The description for the journal line + displayName: Description + required: true + type: String + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Array + required: true + type: Object + required: true + type: Array + journalRef: + description: Reference to the journal in which this journal entry was created + displayName: Journal Reference + properties: + id: + description: The reference identifier for the journal + displayName: Identifier + required: true + type: String + name: + description: The name of the journal + displayName: Name + required: true + type: String + required: true + type: Object + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + recordRef: + description: Reference to the record for which this journal entry was created + displayName: Record Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + updatedOn: + description: The date in which the journal was last updated in the originating system + displayName: Updated On + required: true + type: DateTime + required: true + type: Object + Xero: + value: + displayName: JournalEntry + properties: + journalLines: + description: A collection of detail lines that represent the transactions associated in this entry + displayName: Journal Lines + properties: + accountRef: + description: Reference to the nominal account the line is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: JournalLines.AccountRef + warnings: [] + description: + description: The description for the journal line + displayName: Description + required: true + type: String + validation: + information: + - details: Must not be longer than 4000 characters long and must be the same for all lines. + field: JournalLines.Description + warnings: [] + netAmount: + description: The amount for the journal line, excluding tax + displayName: Net Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: JournalLines.NetAmount + warnings: [] + tracking: + description: Information this item is being tracked against + displayName: Tracking + properties: + recordRefs: + description: A collection of records this item is being tracked against + displayName: Record References + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must not be a parent tracking category. + field: RecordRefs.Id + - details: Must be provided. + field: RecordRefs.Id + warnings: [] + required: false + type: Array + validation: + information: + - details: Tracking categories must not have the same parent tracking category. + field: Tracking.RecordRefs + - details: Maximum of 2 Tracking Categories. + field: Tracking.RecordRefs + warnings: [] + required: false + type: Object + required: true + type: Array + validation: + information: + - details: At least 2 must be provided. + field: JournalLines + warnings: [] + postedOn: + description: The date the entry was posted in the originating system + displayName: Posted On + required: true + type: DateTime + validation: + information: + - details: If no date is specified, it will default to today's date. + field: PostedOn + warnings: [] + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create journal entry model + tags: + - Journal entries + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/journals": + get: + description: |- + Get create journal model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=journals) for integrations that support creating journals. + operationId: get-create-journals-model + responses: + "200": + content: + application/json: + examples: + Sage Intacct: + value: + displayName: Journal + properties: + journalCode: + description: The number or code for the journal + displayName: Journal Number + required: true + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 16 characters + field: JournalCode + name: + description: The name of the journal + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 40 characters + field: Name + status: + description: The status of the journal + displayName: Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + required: true + type: Object + Sandbox: + value: + displayName: Journal + properties: + createdOn: + description: The date the journal was created in the originating system + displayName: Created On + required: true + type: DateTime + hasChildren: + description: If a journal has children, the journal is parent of those children journals + displayName: Has Children + required: true + type: Boolean + journalCode: + description: The number or code for the journal + displayName: Journal Number + required: true + type: String + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + name: + description: The name of the journal + displayName: Name + required: true + type: String + parentId: + description: Identifier for the parent journal - empty if journal is the parent + displayName: Parent Id + required: true + type: String + status: + description: The status of the journal + displayName: Status + required: true + type: String + type: + description: The type of journal + displayName: Type + required: true + type: String + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create journal model + tags: + - Journals + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/payments": + get: + description: |- + Get create payment model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=payments) for integrations that support creating payments. + operationId: get-create-payments-model + responses: + "200": + content: + application/json: + examples: + FreeAgent: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must match the sum of the link amounts. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: CreditNote + required: false + type: String + value: CreditNote + - displayName: Other + required: false + type: String + value: Other + required: true + type: String + required: true + type: Array + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line may be specified + field: Lines + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of the line amounts. + field: TotalAmount + required: true + type: Object + FreshBooks: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + currency: + description: Currency of the payment + displayName: Currency + options: + - displayName: AED + required: false + type: Array + value: AED + - displayName: AFN + required: false + type: Array + value: AFN + - displayName: ALL + required: false + type: Array + value: ALL + - displayName: AMD + required: false + type: Array + value: AMD + - displayName: ANG + required: false + type: Array + value: ANG + - displayName: AOA + required: false + type: Array + value: AOA + - displayName: ARS + required: false + type: Array + value: ARS + - displayName: AUD + required: false + type: Array + value: AUD + - displayName: AWG + required: false + type: Array + value: AWG + - displayName: AZN + required: false + type: Array + value: AZN + - displayName: BAM + required: false + type: Array + value: BAM + - displayName: BBD + required: false + type: Array + value: BBD + - displayName: BDT + required: false + type: Array + value: BDT + - displayName: BGN + required: false + type: Array + value: BGN + - displayName: BHD + required: false + type: Array + value: BHD + - displayName: BIF + required: false + type: Array + value: BIF + - displayName: BMD + required: false + type: Array + value: BMD + - displayName: BND + required: false + type: Array + value: BND + - displayName: BOB + required: false + type: Array + value: BOB + - displayName: BRL + required: false + type: Array + value: BRL + - displayName: BSD + required: false + type: Array + value: BSD + - displayName: BTN + required: false + type: Array + value: BTN + - displayName: BWP + required: false + type: Array + value: BWP + - displayName: BYR + required: false + type: Array + value: BYR + - displayName: BZD + required: false + type: Array + value: BZD + - displayName: CAD + required: false + type: Array + value: CAD + - displayName: CDF + required: false + type: Array + value: CDF + - displayName: CHF + required: false + type: Array + value: CHF + - displayName: CLP + required: false + type: Array + value: CLP + - displayName: CNY + required: false + type: Array + value: CNY + - displayName: COP + required: false + type: Array + value: COP + - displayName: CRC + required: false + type: Array + value: CRC + - displayName: CUC + required: false + type: Array + value: CUC + - displayName: CUP + required: false + type: Array + value: CUP + - displayName: CVE + required: false + type: Array + value: CVE + - displayName: CZK + required: false + type: Array + value: CZK + - displayName: DJF + required: false + type: Array + value: DJF + - displayName: DKK + required: false + type: Array + value: DKK + - displayName: DOP + required: false + type: Array + value: DOP + - displayName: DZD + required: false + type: Array + value: DZD + - displayName: EGP + required: false + type: Array + value: EGP + - displayName: ERN + required: false + type: Array + value: ERN + - displayName: ETB + required: false + type: Array + value: ETB + - displayName: EUR + required: false + type: Array + value: EUR + - displayName: FJD + required: false + type: Array + value: FJD + - displayName: FKP + required: false + type: Array + value: FKP + - displayName: GBP + required: false + type: Array + value: GBP + - displayName: GEL + required: false + type: Array + value: GEL + - displayName: GGP + required: false + type: Array + value: GGP + - displayName: GHS + required: false + type: Array + value: GHS + - displayName: GIP + required: false + type: Array + value: GIP + - displayName: GMD + required: false + type: Array + value: GMD + - displayName: GNF + required: false + type: Array + value: GNF + - displayName: GTQ + required: false + type: Array + value: GTQ + - displayName: GYD + required: false + type: Array + value: GYD + - displayName: HKD + required: false + type: Array + value: HKD + - displayName: HNL + required: false + type: Array + value: HNL + - displayName: HRK + required: false + type: Array + value: HRK + - displayName: HTG + required: false + type: Array + value: HTG + - displayName: HUF + required: false + type: Array + value: HUF + - displayName: IDR + required: false + type: Array + value: IDR + - displayName: ILS + required: false + type: Array + value: ILS + - displayName: IMP + required: false + type: Array + value: IMP + - displayName: INR + required: false + type: Array + value: INR + - displayName: IQD + required: false + type: Array + value: IQD + - displayName: IRR + required: false + type: Array + value: IRR + - displayName: ISK + required: false + type: Array + value: ISK + - displayName: JEP + required: false + type: Array + value: JEP + - displayName: JMD + required: false + type: Array + value: JMD + - displayName: JOD + required: false + type: Array + value: JOD + - displayName: JPY + required: false + type: Array + value: JPY + - displayName: KES + required: false + type: Array + value: KES + - displayName: KGS + required: false + type: Array + value: KGS + - displayName: KHR + required: false + type: Array + value: KHR + - displayName: KMF + required: false + type: Array + value: KMF + - displayName: KPW + required: false + type: Array + value: KPW + - displayName: KRW + required: false + type: Array + value: KRW + - displayName: KWD + required: false + type: Array + value: KWD + - displayName: KYD + required: false + type: Array + value: KYD + - displayName: KZT + required: false + type: Array + value: KZT + - displayName: LAK + required: false + type: Array + value: LAK + - displayName: LBP + required: false + type: Array + value: LBP + - displayName: LKR + required: false + type: Array + value: LKR + - displayName: LRD + required: false + type: Array + value: LRD + - displayName: LSL + required: false + type: Array + value: LSL + - displayName: LYD + required: false + type: Array + value: LYD + - displayName: MAD + required: false + type: Array + value: MAD + - displayName: MDL + required: false + type: Array + value: MDL + - displayName: MGA + required: false + type: Array + value: MGA + - displayName: MKD + required: false + type: Array + value: MKD + - displayName: MMK + required: false + type: Array + value: MMK + - displayName: MNT + required: false + type: Array + value: MNT + - displayName: MOP + required: false + type: Array + value: MOP + - displayName: MRO + required: false + type: Array + value: MRO + - displayName: MUR + required: false + type: Array + value: MUR + - displayName: MVR + required: false + type: Array + value: MVR + - displayName: MWK + required: false + type: Array + value: MWK + - displayName: MXN + required: false + type: Array + value: MXN + - displayName: MYR + required: false + type: Array + value: MYR + - displayName: MZN + required: false + type: Array + value: MZN + - displayName: NAD + required: false + type: Array + value: NAD + - displayName: NGN + required: false + type: Array + value: NGN + - displayName: NIO + required: false + type: Array + value: NIO + - displayName: NOK + required: false + type: Array + value: NOK + - displayName: NPR + required: false + type: Array + value: NPR + - displayName: NZD + required: false + type: Array + value: NZD + - displayName: OMR + required: false + type: Array + value: OMR + - displayName: PAB + required: false + type: Array + value: PAB + - displayName: PEN + required: false + type: Array + value: PEN + - displayName: PGK + required: false + type: Array + value: PGK + - displayName: PHP + required: false + type: Array + value: PHP + - displayName: PKR + required: false + type: Array + value: PKR + - displayName: PLN + required: false + type: Array + value: PLN + - displayName: PYG + required: false + type: Array + value: PYG + - displayName: QAR + required: false + type: Array + value: QAR + - displayName: RON + required: false + type: Array + value: RON + - displayName: RSD + required: false + type: Array + value: RSD + - displayName: RUB + required: false + type: Array + value: RUB + - displayName: RWF + required: false + type: Array + value: RWF + - displayName: SAR + required: false + type: Array + value: SAR + - displayName: SBD + required: false + type: Array + value: SBD + - displayName: SCR + required: false + type: Array + value: SCR + - displayName: SDG + required: false + type: Array + value: SDG + - displayName: SEK + required: false + type: Array + value: SEK + - displayName: SGD + required: false + type: Array + value: SGD + - displayName: SHP + required: false + type: Array + value: SHP + - displayName: SLL + required: false + type: Array + value: SLL + - displayName: SOS + required: false + type: Array + value: SOS + - displayName: SPL + required: false + type: Array + value: SPL + - displayName: SRD + required: false + type: Array + value: SRD + - displayName: STD + required: false + type: Array + value: STD + - displayName: SVC + required: false + type: Array + value: SVC + - displayName: SYP + required: false + type: Array + value: SYP + - displayName: SZL + required: false + type: Array + value: SZL + - displayName: THB + required: false + type: Array + value: THB + - displayName: TJS + required: false + type: Array + value: TJS + - displayName: TMT + required: false + type: Array + value: TMT + - displayName: TND + required: false + type: Array + value: TND + - displayName: TOP + required: false + type: Array + value: TOP + - displayName: TRY + required: false + type: Array + value: TRY + - displayName: TTD + required: false + type: Array + value: TTD + - displayName: TVD + required: false + type: Array + value: TVD + - displayName: TWD + required: false + type: Array + value: TWD + - displayName: TZS + required: false + type: Array + value: TZS + - displayName: UAH + required: false + type: Array + value: UAH + - displayName: UGX + required: false + type: Array + value: UGX + - displayName: USD + required: false + type: Array + value: USD + - displayName: UYU + required: false + type: Array + value: UYU + - displayName: UZS + required: false + type: Array + value: UZS + - displayName: VEF + required: false + type: Array + value: VEF + - displayName: VND + required: false + type: Array + value: VND + - displayName: VUV + required: false + type: Array + value: VUV + - displayName: WST + required: false + type: Array + value: WST + - displayName: XAF + required: false + type: Array + value: XAF + - displayName: XCD + required: false + type: Array + value: XCD + - displayName: XDR + required: false + type: Array + value: XDR + - displayName: XOF + required: false + type: Array + value: XOF + - displayName: XPF + required: false + type: Array + value: XPF + - displayName: YER + required: false + type: Array + value: YER + - displayName: ZAR + required: false + type: Array + value: ZAR + - displayName: ZMW + required: false + type: Array + value: ZMW + - displayName: ZWD + required: false + type: Array + value: ZWD + required: false + type: String + validation: + information: [] + warnings: + - details: Can be used for Payments on Account only + field: Currency + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + required: true + type: String + required: true + type: Array + validation: + information: [] + warnings: + - details: Payment Amount must not exceed Invoice Amount Due or available Customer Credit + field: Lines.Links + - details: Must be a Payment with one Invoice of PaymentOnAccount Link or two links of types Invoice and PaymentOnAccount + field: Lines.Links + required: true + type: Array + validation: + information: [] + warnings: + - details: Only one line is supported + field: Lines + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must be a valid GUID. + field: CustomerRef.Id + - details: Must match the ID of an existing customer. + field: CustomerRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: CustomerRef + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Precision must be maximum of two decimal places. + field: Links.Amount + - details: Must be provided. + field: Links.Amount + warnings: [] + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Id + warnings: [] + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - required: false + type: String + value: Invoice + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines.Links + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines + warnings: [] + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: + - details: Must not be greater than 8 characters long. + field: Reference + warnings: [] + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must equal the sum of the link items amount. + field: TotalAmount + warnings: + - details: Precision must be maximum of two decimal places. + field: TotalAmount + - details: Must be greater than zero. + field: TotalAmount + required: true + type: Object + Oracle NetSuite: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing account of type 'Bank' OR type 'Asset' (with category 'FixedAsset'/'OthAsset'/'OthCurrAsset') OR type 'Liability' (with category 'LongTermLiab'/'OthCurrLiab') OR type 'Expense' (with category 'Expense'/'OthExpense') + field: AccountRef.Id + required: false + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: If the currency is set make sure it's the same as the 'Invoice' and/or 'CreditMemo' currency + field: Currency + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: If the Link Type specified is an 'Invoice' or 'CreditNote' make sure the status is either 'PartiallyPaid' or 'Submitted' + field: Links.Id + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Payment On Account + required: false + type: String + value: PaymentOnAccount + required: true + type: String + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: + - details: This field can be used to provide a tracking category id (Location only) + field: Reference + warnings: + - details: The id format should be 'location-' + field: Reference + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be greater than zero + field: TotalAmount + - details: Must be provided and must be equal to the sum of the lines amounts + field: TotalAmount + required: true + type: Object + QuickBooks Desktop: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Not required if total amount of the payment is 0. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing 'Bank' or 'Other Current Asset' account. + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the customer. + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the customer. + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier. + field: CustomerRef.Id + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Amount plus the sum of amounts in the links must equal 0 + field: Lines.Amount + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Payment On Account + required: false + type: String + value: PaymentOnAccount + required: true + type: String + validation: + information: [] + warnings: + - details: Only 1 link with type 'PaymentOnAccount' may be specified per line, this line may contain no other links + field: Links.Type + - details: Only 1 link with type 'Invoice' may be specified per line + field: Links.Type + required: true + type: Array + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 20 characters. + field: Reference + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the sum of amounts in the lines + field: TotalAmount + required: true + type: Object + QuickBooks Online: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: + - details: Must match the ID of an existing Account. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company + field: Currency + warnings: [] + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be the ID of the Customer associated with the Invoice, Credit Note or Payment On Account. + field: CustomerRef + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Payment On Account + required: false + type: String + value: PaymentOnAccount + required: true + type: String + required: true + type: Array + required: false + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + paymentMethodRef: + description: Reference to the method of this payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + required: true + type: String + required: false + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: + - details: Must match the ID of an existing Account. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company + field: Currency + warnings: [] + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + validation: + information: + - details: Must be the ID of the Customer associated with the Invoice, Credit Note or Payment On Account. + field: CustomerRef + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Payment On Account + required: false + type: String + value: PaymentOnAccount + required: true + type: String + required: true + type: Array + required: false + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + paymentMethodRef: + description: Reference to the method of this payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + required: true + type: String + required: false + type: Object + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Sage 50 (UK): + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: The bank account to pay this invoice from. + displayName: Bank Account + properties: + id: + description: Nominal code of the bank account. + displayName: Account Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account and have a max length of 8 characters. + field: accountRef.id + required: true + type: Object + customerRef: + description: Customer to be paid. + displayName: Customer + properties: + id: + description: Identifier of the customer. + displayName: Customer Id + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer and have a max length of 8 characters. + field: customerRef.id + required: true + type: Object + date: + description: The date this payment was issued. + displayName: Issue Date + required: true + type: Number + lines: + description: Line items of the payment. + displayName: Line Items + properties: + amount: + description: The amount of this line item + displayName: Amount + required: true + type: Number + validation: + information: + - details: this must equal the negative of the sum of the link amounts + warnings: [] + links: + description: Links to the invoice being paid. + displayName: Links + properties: + amount: + description: The amount to be added to the value of the invoice + displayName: Amount + required: true + type: Number + validation: + information: + - details: When paying off an invoice, this value will be negative + warnings: [] + id: + description: The ID of the invoice to pay + displayName: Invoice Id + required: true + type: String + type: + description: The type of the item to be paid + displayName: Payment Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: Payment On Account + required: false + type: String + value: PaymentOnAccount + - displayName: Refund + required: false + type: String + value: Refund + - displayName: Credit Note + required: false + type: String + value: CreditNote + - displayName: Payment + required: false + type: String + value: Payment + required: true + type: String + required: true + type: Array + required: true + type: Array + validation: + information: + - details: Sage 50 only supports one line item per invoice payment so all lines will be merged together in the response. + warnings: [] + note: + description: A description of the payment. + displayName: Note + required: false + type: Number + reference: + description: The user reference for this invoice payment. + displayName: Reference + required: false + type: Number + totalAmount: + description: The total amount being paid to the customer. + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: This must equal the sum of the line amounts + warnings: [] + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be provided. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing Account. + field: AccountRef.Id + required: false + type: Object + validation: + information: [] + warnings: + - details: Required unless the Payment is only allocating a Credit Note. + field: AccountRef + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + validation: + information: + - details: If supplied, must match the currency of the customer. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must match the ID of an existing Customer. + field: CustomerRef.Id + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Links.Amount + warnings: + - details: Must be greater than zero except when Type is Invoice + field: Links.Amount + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Id + warnings: [] + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: PaymentOnAccount + required: false + type: String + value: PaymentOnAccount + - displayName: Refund + required: false + type: String + value: Refund + - displayName: CreditNote + required: false + type: String + value: CreditNote + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines.Links + warnings: [] + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 25 characters. + field: Note + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: TotalAmount + warnings: + - details: Must be zero when allocating against Invoices using a Credit Note only. + field: TotalAmount + - details: Must equal the sum of the link items amount. + field: TotalAmount + required: true + type: Object + Sage Intacct: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: For undeposited payments use the GL account record number to charge. + field: AccountRef.Id + - details: To charge either a savings, checking or credit card account use its associated GL account number. + field: AccountRef.Id + warnings: [] + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: false + type: String + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + validation: + information: + - details: Is required if currency is provided. + field: CurrencyRate + warnings: [] + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be an existing customer ID in Sage Intacct. + field: CustomerRef.Id + warnings: [] + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must occur after the date the invoice was created. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: When added together with the sum of the Links.Amount the total must be zero. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must not be more than the total amount due for an invoice or the available funds in the account to be charged. + field: Links.Amount + warnings: [] + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be a valid Record No. from accounts receivable of either an invoice for an 'Invoice', adjustment for a 'CreditNote' or an advance for a 'PaymentOnAccount' in Sage Intacct. + field: Links.Id + - details: Must be an integer. + field: Links.Id + - details: Must related to CustomerRef.Id in Sage Intacct. + field: Links.Id + warnings: [] + type: + description: The type of transaction that is being linked + displayName: Link Type + required: true + type: String + validation: + information: + - details: Must be one of Invoiceor CreditNoteor PaymentOnAccount. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: No more than two links can exist when paying for an invoice via a CreditNoteor PaymentOnAccount. + field: Lines.Links + - details: Must contain only one Invoice. + field: Lines.Links + warnings: [] + required: true + type: Array + validation: + information: + - details: Must contain at least one payment line. + field: Lines + warnings: [] + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + validation: + information: + - details: Must be less than 1000 characters. + field: Note + warnings: [] + paymentMethodRef: + description: Reference to the method of this payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + options: + - displayName: Printed Check + required: false + type: String + value: "1" + - displayName: Credit Card + required: false + type: String + value: "3" + - displayName: EFT + required: false + type: String + value: "5" + - displayName: Cash + required: false + type: String + value: "6" + required: true + type: String + required: true + type: Object + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + validation: + information: + - details: Can be used to set the Document/Check No. in Sage Intacct. + field: Reference + warnings: [] + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must equal the sum of Lines.Amount. + field: TotalAmount + warnings: [] + required: true + type: Object + validation: + information: + - details: Sage Intacct handles allocated payments only. + warnings: [] + Sandbox: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + companyName: + description: The name of the customer referenced by the identifier + displayName: Name + required: true + type: String + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + allocatedOnDate: + description: The date the payment was allocated + displayName: Allocated On Date + required: true + type: DateTime + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + currencyRate: + description: The exchange rate between the currency of the payment and the currency of the linked transaction + displayName: Currency Exchange Rate + required: true + type: Number + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + required: true + type: String + required: true + type: Array + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Any additional text based information associated with the payment + displayName: Note + required: true + type: String + paymentMethodRef: + description: Reference to the method of this payment + displayName: Payment Method Reference + properties: + id: + description: The reference identifier for the payment method + displayName: Identifier + required: true + type: String + name: + description: The name of the payment method referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + reference: + description: A user friendly reference for the payment + displayName: Reference + required: true + type: String + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + required: true + type: Object + Xero: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: + - details: Must be either a type of BANK account or enable payments must be switched on. + field: AccountRef.Id + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: AccountRef + warnings: [] + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: + - details: Must be provided. + field: Currency + warnings: [] + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: false + type: Number + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be provided. + field: CustomerRef.Id + warnings: + - details: Must be a valid GUID. + field: CustomerRef.Id + - details: Must match the ID of an existing account. + field: CustomerRef.Id + required: true + type: Object + validation: + information: + - details: Must be provided. + field: CustomerRef + warnings: [] + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + lines: + description: A collection of payment lines + displayName: Lines + properties: + amount: + description: The total amount for the line in the payment currency + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Lines.Amount + warnings: [] + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be provided. + field: Links.Amount + warnings: [] + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + validation: + information: + - details: Invoice and Credit Note ID must be provided in order to allocate a Credit Note to an Invoice. + field: Links.Id + - details: Must be provided. + field: Links.Id + warnings: + - details: Must be a valid GUID. + field: Links.Id + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: String + value: Invoice + - displayName: CreditNote + required: false + type: String + value: CreditNote + - displayName: Payment + required: false + type: String + value: Payment + required: true + type: String + validation: + information: + - details: Must be provided. + field: Links.Type + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines.Links + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Lines + warnings: [] + reference: + description: A user friendly reference for the payment + displayName: Reference + required: false + type: String + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: + - details: Must be provided and must equal the sum of the link items amount. + field: TotalAmount + warnings: + - details: Must be greater than 0, unless the payment is a credit note allocation. + field: TotalAmount + required: true + type: Object + Zoho Books: + value: + description: A payment represents an allocation of transactions across an 'accounts receivable' account (customer) + displayName: Payment + properties: + accountRef: + description: Reference to the nominal account the payment is linked to + displayName: Nominal Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: AccountRef.ID is required when making a payment to an invoice and/or a payment on account + field: AccountRef.Id + required: true + type: Object + currency: + description: Currency of the payment + displayName: Currency + required: true + type: String + validation: + information: [] + warnings: + - details: must match the currency of any invoices or credit notes + field: Currency + currencyRate: + description: The exchange rate between the currency of the payment and the base currency of the company + displayName: Currency Exchange Rate + required: true + type: Number + customerRef: + description: Reference to the customer the payment has been sent by + displayName: Customer Reference + properties: + id: + description: The reference identifier for the customer + displayName: Identifier + required: true + type: String + required: true + type: Object + date: + description: The date the payment was recorded + displayName: Date + required: true + type: DateTime + lines: + description: A collection of payment lines + displayName: Lines + properties: + links: + description: A collection of linked transactions + displayName: Links + properties: + amount: + description: The amount by which the balance of the linked entity is altered, in the currency of the linked entity + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: the sum of all link amounts must equal the negated total amount of the payment + field: Links.Amount + id: + description: The identifier for the referenced transaction + displayName: Identifier + required: true + type: String + type: + description: The type of transaction that is being linked + displayName: Link Type + options: + - displayName: Invoice + required: false + type: Array + - displayName: CreditNote + required: false + type: Array + - displayName: PaymentOnAccount + required: false + type: Array + required: true + type: String + required: true + type: Array + validation: + information: [] + warnings: + - details: if a credit note link is provided, exactly one invoice link must be provided, otherwise unlimited invoice links and one payment on account link are allowed + field: Lines.Links + required: true + type: Array + note: + description: Any additional text based information associated with the payment + displayName: Note + required: false + type: String + totalAmount: + description: The total amount of the payment, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: must be greater than or equal to 0 + field: TotalAmount + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create payment model + tags: + - Payments + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/purchaseOrders": + get: + description: |- + Get create/update purchase order model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=purchaseOrders) for integrations that support creating and updating purchase orders. + operationId: get-create-update-purchaseOrders-model + responses: + "200": + content: + application/json: + examples: + Oracle NetSuite: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: true + type: String + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: true + type: Number + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: false + type: DateTime + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + accountRef: + description: Reference to the account to which the line item is linked + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should not be a bank account + field: LineItems.AccountRef + - details: Should only be specified when pushing an expense + field: LineItems.AccountRef + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: false + type: String + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should only be specified when pushing an item (not an expense) + field: LineItems.ItemRef + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: false + type: Number + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + required: false + type: Object + validation: + information: [] + warnings: + - details: Should be specified when item type is not 'Discount' + field: LineItems.TaxRateRef + trackingCategoryRefs: + description: Reference to the tracking categories to which the line item is linked + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + required: false + type: Array + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: false + type: Number + required: true + type: Array + note: + description: Any additional information associated with the payment + displayName: Note + required: false + type: String + status: + description: Current state of the purchase order + displayName: Status + options: + - displayName: Open + required: false + type: String + value: Open + required: true + type: String + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Desktop: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the default currency of the customer + field: Currency + warnings: + - details: Must be a three letter ISO code that matches the currency of the customer + field: Currency + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: Currency + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: false + type: Number + validation: + information: + - details: If not set, will default to the rate set within QuickBooks Desktop, if no rate is set in QuickBooks Desktop, it will default to 1. + field: CurrencyRate + - details: Can only be set if the Quickbooks Desktop company has Multicurrency enabled. + field: CurrencyRate + warnings: [] + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: false + type: DateTime + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: LineItems.Description + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.ItemRef + required: true + type: Object + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: true + type: Number + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Only valid for UK or CA versions of QuickBooks Desktop with VAT enabled, will be ignored in US version + field: TaxRateRef.Id + - details: Must match the ID of an existing tax rate + field: TaxRateRef.Id + required: false + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: Reference to the tracking categories to which the line item is linked + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tracking category. + field: TrackingCategoryRefs.Id + required: false + type: Array + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Any additional information associated with the payment + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4000 characters. + field: Note + paymentDueDate: + description: Date the supplier is due to be paid + displayName: Payment Due Date + required: false + type: DateTime + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 11 characters. + field: PurchaseOrderNumber + shipTo: + description: Delivery details for any goods that have been ordered + displayName: Ship To + properties: + address: + description: Delivery address for any goods that have been ordered + displayName: Address + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Address.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Address.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Address.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Address.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 13 characters. + field: Address.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 21 characters. + field: Address.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: true + type: String + validation: + information: + - details: Only 1 address each of type(s) Delivery may be specified. + field: Address.Type + warnings: [] + required: false + type: Object + required: false + type: Object + status: + description: Current state of the purchase order + displayName: Status + options: + - displayName: Open + required: false + type: String + value: Open + required: true + type: String + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing supplier. + field: SupplierRef.Id + required: true + type: Object + totalAmount: + description: Total amount of the purchase order, including discounts and tax + displayName: Total Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must match the total amount in the line items. + field: TotalAmount + required: true + type: Object + QuickBooks Online: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + deliveryDate: + description: Actual delivery date for any goods that have been ordered + displayName: Delivery Date + required: false + type: DateTime + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: false + type: DateTime + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used + field: IssueDate + warnings: [] + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + accountRef: + description: Reference to the account to which the line item is linked + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + validation: + information: + - details: Required if the expense line is account based. If AccountRef is specified, ItemRef must be null. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + discountAmount: + description: Value of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: + - details: Required if the expense line is item based. If ItemRef is specified, AccountRef must be null. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: true + type: Number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total + required: true + type: Number + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Any additional information associated with the payment + displayName: Note + required: false + type: String + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: false + type: String + shipTo: + description: Delivery details for any goods that have been ordered + displayName: Ship To + required: false + type: Object + status: + description: Current state of the purchase order + displayName: Status + options: + - displayName: Open + required: false + type: String + value: Open + required: true + type: String + validation: + information: + - details: QuickBooks Online only supports "Open" as a status for new purchase orders. + field: Status + warnings: [] + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: false + type: String + validation: + information: + - details: Required if multi-currency is enabled for the company. + field: Currency + warnings: [] + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: false + type: Number + validation: + information: + - details: Required if Currency is not the base currency. + field: CurrencyRate + warnings: [] + deliveryDate: + description: Actual delivery date for any goods that have been ordered + displayName: Delivery Date + required: false + type: DateTime + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: false + type: DateTime + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: false + type: DateTime + validation: + information: + - details: If the issue date is not supplied, the current date on the server is used + field: IssueDate + warnings: [] + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + accountRef: + description: Reference to the account to which the line item is linked + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: false + type: String + validation: + information: + - details: Required if the expense line is account based. If AccountRef is specified, ItemRef must be null. + field: AccountRef.Id + warnings: + - details: Must match the ID of an existing account. + field: AccountRef.Id + required: true + type: Object + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: false + type: String + validation: + information: [] + warnings: + - details: Should not be longer than 4000 characters. + field: LineItems.Description + discountAmount: + description: Value of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: + - details: Required if the expense line is item based. If ItemRef is specified, AccountRef must be null. + field: ItemRef.Id + warnings: + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: true + type: Object + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: true + type: Number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total + required: true + type: Number + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax code. + field: TaxRateRef.Id + required: true + type: Object + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + note: + description: Any additional information associated with the payment + displayName: Note + required: false + type: String + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: false + type: String + shipTo: + description: Delivery details for any goods that have been ordered + displayName: Ship To + required: false + type: Object + status: + description: Current state of the purchase order + displayName: Status + options: + - displayName: Open + required: false + type: String + value: Open + required: true + type: String + validation: + information: + - details: QuickBooks Online only supports "Open" as a status for new purchase orders. + field: Status + warnings: [] + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + Sandbox: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: true + type: String + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: true + type: Number + deliveryDate: + description: Actual delivery date for any goods that have been ordered + displayName: Delivery Date + required: true + type: DateTime + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: true + type: DateTime + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: true + type: DateTime + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + accountRef: + description: Reference to the account to which the line item is linked + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + name: + description: Name of the account + displayName: Name + required: true + type: String + required: true + type: Object + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: true + type: String + discountAmount: + description: Value of any discounts applied + displayName: Discount Amount + required: true + type: Number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount + displayName: Discount Percentage + required: true + type: Number + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: true + type: String + name: + description: The name of the item referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: true + type: Number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax + displayName: Sub Total + required: true + type: Number + taxAmount: + description: Amount of tax for the line + displayName: Tax Amount + required: true + type: Number + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + effectiveTaxRate: + description: The total applied tax percentage, including compounding details + displayName: Effective Tax Rate + required: true + type: Number + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: true + type: String + name: + description: The name of the tax rate referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: The total amount of the line, inclusive of discounts and tax + displayName: Total Amount + required: true + type: Number + trackingCategoryRefs: + description: Reference to the tracking categories to which the line item is linked + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + note: + description: Any additional information associated with the payment + displayName: Note + required: true + type: String + paymentDueDate: + description: Date the supplier is due to be paid + displayName: Payment Due Date + required: true + type: DateTime + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: true + type: String + shipTo: + description: Delivery details for any goods that have been ordered + displayName: Ship To + properties: + address: + description: Delivery address for any goods that have been ordered + displayName: Address + properties: + city: + description: The third line of the address, or city + displayName: City + required: true + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: true + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: true + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: true + type: String + type: + description: The type of the address + displayName: Address Type + required: true + type: String + required: true + type: Object + contact: + description: Details of the named contact at the delivery address + displayName: Contact + properties: + email: + description: Email address of the contact at the delivery address + displayName: Email + required: true + type: String + name: + description: Name of the contact at the delivery address + displayName: Name + required: true + type: String + phone: + description: Phone number of the contact at the delivery address + displayName: Phone + required: true + type: String + required: true + type: Object + required: true + type: Object + status: + description: Current state of the purchase order + displayName: Status + required: true + type: String + subTotal: + description: Total amount of the purchase order, including discounts but excluding tax + displayName: Sub Total + required: true + type: Number + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + supplierName: + description: The name of the supplier referenced by the identifier + displayName: Name + required: true + type: String + required: true + type: Object + totalAmount: + description: Total amount of the purchase order, including discounts and tax + displayName: Total Amount + required: true + type: Number + totalDiscount: + description: Total value of any discounts applied to the purchase order + displayName: Total Discount + required: true + type: Number + totalTaxAmount: + description: Total amount of tax included in the purchase order + displayName: Total Tax Amount + required: true + type: Number + required: true + type: Object + Xero: + value: + description: A purchase order is an official document issued by a buyer to their supplier. It details the types, quantities, and agreed prices of the goods the buyer wishes to purchase + displayName: Purchase Order + properties: + currency: + description: Currency of the purchase order + displayName: Currency + required: false + type: String + currencyRate: + description: Rate for converting the total amount of the purchase order into the base currency for the company + displayName: Currency Rate + required: false + type: Number + validation: + information: + - details: If no rate is specified, the Xero day rate will be applied. + field: CurrencyRate + ref: https://central.xero.com/s/#CurrencySettings$Rates + warnings: [] + deliveryDate: + description: Actual delivery date for any goods that have been ordered + displayName: Delivery Date + required: false + type: DateTime + expectedDeliveryDate: + description: Expected delivery date for any goods that have been ordered + displayName: Expected Delivery Date + required: false + type: DateTime + validation: + information: [] + warnings: + - details: Can only be provided for Purchase Orders with an Open status. + field: ExpectedDeliveryDate + issueDate: + description: Date of the purchase order as recorded in the accounting platform + displayName: Issue Date + required: false + type: DateTime + lineItems: + description: Collection of items that relate to the purchase order + displayName: Line Items + properties: + accountRef: + description: Reference to the account to which the line item is linked + displayName: Account Reference + properties: + id: + description: The identifier for the account + displayName: Account ID + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: AccountRef.Id + - details: Must match the ID of an existing account. + field: AccountRef.Id + - details: Must be provided. + field: AccountRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Must be provided. + field: LineItems.AccountRef + description: + description: Friendly name for the goods that have been ordered + displayName: Description + required: true + type: String + validation: + information: [] + warnings: + - details: Must not exceed 4000 characters. + field: LineItems.Description + discountAmount: + description: Value of any discounts applied + displayName: Discount Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match DiscountPercentage if supplied + field: LineItems.DiscountAmount + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount + displayName: Discount Percentage + required: false + type: Number + validation: + information: [] + warnings: + - details: Must match DiscountAmount if supplied + field: LineItems.DiscountPercentage + itemRef: + description: Reference to the product or inventory item to which the line item is linked + displayName: Item Reference + properties: + id: + description: The reference identifier for the item + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: ItemRef.Id + - details: Must match the ID of an existing item. + field: ItemRef.Id + required: false + type: Object + quantity: + description: Number of units of the goods that have been ordered + displayName: Quantity + required: true + type: Number + validation: + information: [] + warnings: + - details: Must not be negative + field: LineItems.Quantity + taxRateRef: + description: Reference to the tax rate to which the line item is linked + displayName: Tax Rate Reference + properties: + id: + description: The reference identifier for the tax rate + displayName: Identifier + required: false + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing tax rate. + field: TaxRateRef.Id + required: false + type: Object + trackingCategoryRefs: + description: Reference to the tracking categories to which the line item is linked + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be provided. + field: TrackingCategoryRefs.Id + required: false + type: Array + validation: + information: [] + warnings: + - details: Tracking categories must not have the same parent tracking category. + field: LineItems.TrackingCategoryRefs + - details: Maximum of 2 Tracking Categories. + field: LineItems.TrackingCategoryRefs + unitAmount: + description: Price of each unit of the goods + displayName: Unit Amount + required: true + type: Number + required: true + type: Array + validation: + information: [] + warnings: + - details: Must be provided and must not be empty + field: LineItems + note: + description: Any additional information associated with the payment + displayName: Note + required: false + type: String + validation: + information: [] + warnings: + - details: Must not exceed 500 characters. + field: Note + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform + displayName: Purchase Order Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must be unique. + field: PurchaseOrderNumber + shipTo: + description: Delivery details for any goods that have been ordered + displayName: Ship To + properties: + address: + description: Delivery address for any goods that have been ordered + displayName: Address + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Object + contact: + description: Details of the named contact at the delivery address + displayName: Contact + properties: + name: + description: Name of the contact at the delivery address + displayName: Name + required: false + type: String + phone: + description: Phone number of the contact at the delivery address + displayName: Phone + required: false + type: String + required: false + type: Object + required: false + type: Object + status: + description: Current state of the purchase order + displayName: Status + options: + - displayName: Draft + required: false + type: String + value: Draft + - displayName: Open + required: false + type: String + value: Open + - displayName: Closed + required: false + type: String + value: Closed + required: true + type: String + validation: + information: [] + warnings: + - details: ExpectedDeliveryDate can only be provided for Purchase Orders with an Open status. + field: Status + - details: Must be provided. + field: Status + subTotal: + description: Total amount of the purchase order, including discounts but excluding tax + displayName: Sub Total + required: false + type: Number + supplierRef: + description: Supplier that the purchase order is recorded against in the accounting system + displayName: Supplier Reference + properties: + id: + description: The reference identifier for the supplier + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a valid GUID. + field: SupplierRef.Id + - details: Must match the ID of an existing Supplier. + field: SupplierRef.Id + - details: Must be provided. + field: SupplierRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Must be provided. + field: SupplierRef + totalAmount: + description: Total amount of the purchase order, including discounts and tax + displayName: Total Amount + required: false + type: Number + totalDiscount: + description: Total value of any discounts applied to the purchase order + displayName: Total Discount + required: false + type: Number + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update purchase order model + tags: + - Purchase orders + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/suppliers": + get: + description: |- + Get create/update supplier model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=suppliers) for integrations that support creating and updating suppliers. + operationId: get-create-update-suppliers-model + responses: + "200": + content: + application/json: + examples: + Exact (Netherlands): + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a 2-letter country code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only the first address provided will be considered, all other entries will be not be recorded + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: false + type: String + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Only for Exact Netherlands, if provided, must be exactly 20 characters in length + field: RegistrationNumber + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Exact (UK): + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Must be a 2-letter country code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only the first address provided will be considered, all other entries will be not be recorded + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: false + type: String + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Only for Exact Netherlands, if provided, must be exactly 20 characters in length + field: RegistrationNumber + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + FreeAgent: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Only one address may be specified + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + MYOB AccountRight and Essentials: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: + - details: Must not be longer than 255 characters. + field: Addresses.City + warnings: [] + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: + - details: Must not be longer than 255 characters. + field: Addresses.Country + warnings: [] + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: + - details: Must not be longer than 127 characters. + field: Addresses.Line1 + warnings: [] + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: + - details: Must not be longer than 127 characters. + field: Addresses.Line2 + warnings: [] + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: + - details: Must not be longer than 11 characters. + field: Addresses.PostalCode + warnings: [] + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: + - details: Must not be longer than 255 characters. + field: Addresses.Region + warnings: [] + required: true + type: Array + validation: + information: + - details: Must be provided. + field: Addresses + warnings: + - details: Must only have 5 address entries at most. + field: Addresses + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + validation: + information: + - details: Must not be longer than 255 characters. + field: EmailAddress + warnings: [] + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + validation: + information: + - details: Must not be longer than 21 characters. + field: Phone + warnings: [] + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + validation: + information: + - details: Must not be longer than 14 characters. + field: RegistrationNumber + warnings: [] + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - required: false + type: String + value: Active + - required: false + type: String + value: Unknown + required: true + type: String + validation: + information: + - details: Must be provided. + field: Status + warnings: [] + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + validation: + information: + - details: Must be provided and must contain a First and Last name separated by a ' '(space). + field: SupplierName + warnings: + - details: Must not have the part after the first name longer than 30 characters. + field: SupplierName + - details: Must not have its first part (i.e. the first name) longer than 20 characters. + field: SupplierName + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + validation: + information: + - details: Must not be longer than 19 characters. + field: TaxNumber + warnings: [] + required: true + type: Object + Oracle NetSuite: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + validation: + information: [] + warnings: + - details: Must be a two letter Country ISO code + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing + required: false + type: String + value: Billing + - displayName: Delivery + required: false + type: String + value: Delivery + - displayName: Unknown + required: false + type: String + value: Unknown + required: true + type: String + required: false + type: Array + validation: + information: + - details: Multiple addresses of Unknown type may be provided + field: Addresses + warnings: + - details: Only one each of Billing and Delivery addresses can be provided + field: Addresses + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + QuickBooks Desktop: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 31 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 13 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 21 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: true + type: String + validation: + information: + - details: Only 1 address each of type(s) Billing/Delivery may be specified. + field: Addresses.Type + warnings: [] + required: false + type: Array + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 25 characters for first and last names + field: ContactName + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + validation: + information: + - details: If not set, will default to the base currency of the QuickBooks Desktop company + field: DefaultCurrency + warnings: + - details: Must be a three letter ISO code that matches an existing, active currency in the QuickBooks Desktop company + field: DefaultCurrency + - details: Can only be set if Multicurrency is enabled within the QuickBooks Desktop company + field: DefaultCurrency + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + validation: + information: [] + warnings: + - details: Max length of 41 characters. + field: SupplierName + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 30 characters. + field: TaxNumber + required: true + type: Object + QuickBooks Online: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: Addresses.PostalCode + - details: Max length of 50 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + required: true + type: String + required: false + type: Array + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: Phone + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + QuickBooks Online Sandbox: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.City + country: + description: The country for the address + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: Addresses.PostalCode + - details: Max length of 50 characters. + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: Addresses.Region + type: + description: The type of the address + displayName: Address Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + required: true + type: String + required: false + type: Array + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: Phone + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Sage 50 (UK): + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: Contact addresses for the supplier. + displayName: Addresses + properties: + city: + description: The city of the supplier address. + displayName: City + required: false + type: String + line1: + description: Line 1 of the supplier address. + displayName: Line 1 + required: true + type: String + line2: + description: Line 2 of the supplier address. + displayName: Line 2 + required: false + type: String + postalCode: + description: Post or Zip code for the address. + displayName: Postal code + required: false + type: String + region: + description: The region of the supplier address. + displayName: Region + required: false + type: String + type: + description: The type of address as it related to the supplier. + displayName: Type + options: + - displayName: Unknown Address + required: false + type: String + value: Unknown + required: false + type: String + validation: + information: + - details: If Address type is not specified, it will default to type ''Unknown'' + field: addresses.type + warnings: [] + required: false + type: Array + validation: + information: [] + warnings: + - details: Only one address can be included in the Addresses array. + field: addresses + contactName: + description: The name of the main contact for the supplier. + displayName: Contact Name + required: false + type: String + validation: + information: [] + warnings: + - details: The contact name can have a maximum of 30 characters + field: contactName + defaultCurrency: + description: If not provided, the currency will default to the company's base currency. + displayName: Default Currency + required: false + type: String + emailAddress: + description: The email address that the supplier may be contacted on. + displayName: Email Address + required: false + type: String + id: + description: ID of the supplier. + displayName: Id + required: true + type: String + validation: + information: + - details: The supplier ID must be all Uppercase, if it is not, it will be converted to Uppercase before pushing. + field: id + warnings: + - details: The supplier ID must be unique, contain no spaces and have a maximum of 8 characters. + field: id + phone: + description: The telephone number that the supplier may be contacted on. + displayName: Telephone + required: false + type: String + status: + description: The status of the supplier. + displayName: Status + options: + - displayName: Active Status + required: false + type: String + value: Active + required: false + type: String + supplierName: + description: Name of the supplier. + displayName: Name + required: true + type: String + validation: + information: [] + warnings: + - details: The supplier name can have a maximum of 60 characters + field: supplierName + taxNumber: + description: Legal company registration identifier. + displayName: Tax Number + required: false + type: String + required: true + type: Object + validation: + information: + - details: Pushing to Sage 50 2015 (v21) or below is not supported. To enable push, please upgrade to at least Sage 50 2016 (v22) and re-sync the company. + warnings: [] + Sage Business Cloud Accounting: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + country: + description: The country for the address + displayName: Country + options: + - displayName: Afghanistan (AF) + required: false + type: String + value: Afghanistan (AF) + - displayName: Albania (AL) + required: false + type: String + value: Albania (AL) + - displayName: Algeria (DZ) + required: false + type: String + value: Algeria (DZ) + - displayName: Andorra (AD) + required: false + type: String + value: Andorra (AD) + - displayName: Angola (AO) + required: false + type: String + value: Angola (AO) + - displayName: Argentina (AR) + required: false + type: String + value: Argentina (AR) + - displayName: Armenia (AM) + required: false + type: String + value: Armenia (AM) + - displayName: Aruba (AW) + required: false + type: String + value: Aruba (AW) + - displayName: Australia (AU) + required: false + type: String + value: Australia (AU) + - displayName: Austria (AT) + required: false + type: String + value: Austria (AT) + - displayName: Azerbaijan (AZ) + required: false + type: String + value: Azerbaijan (AZ) + - displayName: Bahamas (BS) + required: false + type: String + value: Bahamas (BS) + - displayName: Bahrain (BH) + required: false + type: String + value: Bahrain (BH) + - displayName: Bangladesh (BD) + required: false + type: String + value: Bangladesh (BD) + - displayName: Barbados (BB) + required: false + type: String + value: Barbados (BB) + - displayName: Belarus (BY) + required: false + type: String + value: Belarus (BY) + - displayName: Belgium (BE) + required: false + type: String + value: Belgium (BE) + - displayName: Belize (BZ) + required: false + type: String + value: Belize (BZ) + - displayName: Benin (BJ) + required: false + type: String + value: Benin (BJ) + - displayName: Bermuda (BM) + required: false + type: String + value: Bermuda (BM) + - displayName: Bhutan (BT) + required: false + type: String + value: Bhutan (BT) + - displayName: Bolivia (BO) + required: false + type: String + value: Bolivia (BO) + - displayName: Bosnia and Herzegovina (BA) + required: false + type: String + value: Bosnia and Herzegovina (BA) + - displayName: Botswana (BW) + required: false + type: String + value: Botswana (BW) + - displayName: Brazil (BR) + required: false + type: String + value: Brazil (BR) + - displayName: British Virgin Islands (VG) + required: false + type: String + value: British Virgin Islands (VG) + - displayName: Brunei Darussalam (BN) + required: false + type: String + value: Brunei Darussalam (BN) + - displayName: Bulgaria (BG) + required: false + type: String + value: Bulgaria (BG) + - displayName: Burkina Faso (BF) + required: false + type: String + value: Burkina Faso (BF) + - displayName: Burundi (BI) + required: false + type: String + value: Burundi (BI) + - displayName: Cambodia (KH) + required: false + type: String + value: Cambodia (KH) + - displayName: Cameroon (CM) + required: false + type: String + value: Cameroon (CM) + - displayName: Canada (CA) + required: false + type: String + value: Canada (CA) + - displayName: Cape Verde (CV) + required: false + type: String + value: Cape Verde (CV) + - displayName: Cayman Islands (KY) + required: false + type: String + value: Cayman Islands (KY) + - displayName: Central African Republic (CF) + required: false + type: String + value: Central African Republic (CF) + - displayName: Chad (TD) + required: false + type: String + value: Chad (TD) + - displayName: Chile (CL) + required: false + type: String + value: Chile (CL) + - displayName: China (CN) + required: false + type: String + value: China (CN) + - displayName: Colombia (CO) + required: false + type: String + value: Colombia (CO) + - displayName: Comoros (KM) + required: false + type: String + value: Comoros (KM) + - displayName: Congo (CG) + required: false + type: String + value: Congo (CG) + - displayName: Costa Rica (CR) + required: false + type: String + value: Costa Rica (CR) + - displayName: Croatia (HR) + required: false + type: String + value: Croatia (HR) + - displayName: Cuba (CU) + required: false + type: String + value: Cuba (CU) + - displayName: Cura�ao (CW) + required: false + type: String + value: Cura�ao (CW) + - displayName: Cyprus (CY) + required: false + type: String + value: Cyprus (CY) + - displayName: Czech Republic (CZ) + required: false + type: String + value: Czech Republic (CZ) + - displayName: Democratic Republic of the Congo (CD) + required: false + type: String + value: Democratic Republic of the Congo (CD) + - displayName: Denmark (DK) + required: false + type: String + value: Denmark (DK) + - displayName: Djibouti (DJ) + required: false + type: String + value: Djibouti (DJ) + - displayName: Dominica (DM) + required: false + type: String + value: Dominica (DM) + - displayName: Dominican Republic (DO) + required: false + type: String + value: Dominican Republic (DO) + - displayName: East Timor (TP) + required: false + type: String + value: East Timor (TP) + - displayName: Ecuador (EC) + required: false + type: String + value: Ecuador (EC) + - displayName: Egypt (EG) + required: false + type: String + value: Egypt (EG) + - displayName: El Salvador (SV) + required: false + type: String + value: El Salvador (SV) + - displayName: Equatorial Guinea (GQ) + required: false + type: String + value: Equatorial Guinea (GQ) + - displayName: Eritrea (ER) + required: false + type: String + value: Eritrea (ER) + - displayName: Estonia (EE) + required: false + type: String + value: Estonia (EE) + - displayName: Ethiopia (ET) + required: false + type: String + value: Ethiopia (ET) + - displayName: Falkland Islands (Malvinas) (FK) + required: false + type: String + value: Falkland Islands (Malvinas) (FK) + - displayName: Federated States of Micronesia (FM) + required: false + type: String + value: Federated States of Micronesia (FM) + - displayName: Fiji (FJ) + required: false + type: String + value: Fiji (FJ) + - displayName: Finland (FI) + required: false + type: String + value: Finland (FI) + - displayName: France (FR) + required: false + type: String + value: France (FR) + - displayName: French Polynesia (PF) + required: false + type: String + value: French Polynesia (PF) + - displayName: Gabon (GA) + required: false + type: String + value: Gabon (GA) + - displayName: Gambia (GM) + required: false + type: String + value: Gambia (GM) + - displayName: Georgia (GE) + required: false + type: String + value: Georgia (GE) + - displayName: Germany (DE) + required: false + type: String + value: Germany (DE) + - displayName: Ghana (GH) + required: false + type: String + value: Ghana (GH) + - displayName: Gibraltar (GI) + required: false + type: String + value: Gibraltar (GI) + - displayName: Greece (GR) + required: false + type: String + value: Greece (GR) + - displayName: Greenland (GL) + required: false + type: String + value: Greenland (GL) + - displayName: Grenada (GD) + required: false + type: String + value: Grenada (GD) + - displayName: Guadaloupe (GP) + required: false + type: String + value: Guadaloupe (GP) + - displayName: Guam (GU) + required: false + type: String + value: Guam (GU) + - displayName: Guatemala (GT) + required: false + type: String + value: Guatemala (GT) + - displayName: Guernsey (GG) + required: false + type: String + value: Guernsey (GG) + - displayName: Guinea (GN) + required: false + type: String + value: Guinea (GN) + - displayName: Guinea-Bissau (GW) + required: false + type: String + value: Guinea-Bissau (GW) + - displayName: Guyana (GY) + required: false + type: String + value: Guyana (GY) + - displayName: Haiti (HT) + required: false + type: String + value: Haiti (HT) + - displayName: Honduras (HN) + required: false + type: String + value: Honduras (HN) + - displayName: Hong Kong (HK) + required: false + type: String + value: Hong Kong (HK) + - displayName: Hungary (HU) + required: false + type: String + value: Hungary (HU) + - displayName: Iceland (IS) + required: false + type: String + value: Iceland (IS) + - displayName: India (IN) + required: false + type: String + value: India (IN) + - displayName: Indonesia (ID) + required: false + type: String + value: Indonesia (ID) + - displayName: Iran (IR) + required: false + type: String + value: Iran (IR) + - displayName: Iraq (IQ) + required: false + type: String + value: Iraq (IQ) + - displayName: Ireland (IE) + required: false + type: String + value: Ireland (IE) + - displayName: Israel (IL) + required: false + type: String + value: Israel (IL) + - displayName: Italy (IT) + required: false + type: String + value: Italy (IT) + - displayName: Ivory Coast (CI) + required: false + type: String + value: Ivory Coast (CI) + - displayName: Jamaica (JM) + required: false + type: String + value: Jamaica (JM) + - displayName: Japan (JP) + required: false + type: String + value: Japan (JP) + - displayName: Jersey (JE) + required: false + type: String + value: Jersey (JE) + - displayName: Jordan (JO) + required: false + type: String + value: Jordan (JO) + - displayName: Kazakhstan (KZ) + required: false + type: String + value: Kazakhstan (KZ) + - displayName: Kenya (KE) + required: false + type: String + value: Kenya (KE) + - displayName: Kuwait (KW) + required: false + type: String + value: Kuwait (KW) + - displayName: Kyrgyzstan (KG) + required: false + type: String + value: Kyrgyzstan (KG) + - displayName: Laos (LA) + required: false + type: String + value: Laos (LA) + - displayName: Latvia (LV) + required: false + type: String + value: Latvia (LV) + - displayName: Lebanon (LB) + required: false + type: String + value: Lebanon (LB) + - displayName: Lesotho (LS) + required: false + type: String + value: Lesotho (LS) + - displayName: Liberia (LR) + required: false + type: String + value: Liberia (LR) + - displayName: Libya (LY) + required: false + type: String + value: Libya (LY) + - displayName: Liechtenstein (LI) + required: false + type: String + value: Liechtenstein (LI) + - displayName: Lithuania (LT) + required: false + type: String + value: Lithuania (LT) + - displayName: Luxembourg (LU) + required: false + type: String + value: Luxembourg (LU) + - displayName: Macau (MO) + required: false + type: String + value: Macau (MO) + - displayName: Macedonia (MK) + required: false + type: String + value: Macedonia (MK) + - displayName: Madagascar (MG) + required: false + type: String + value: Madagascar (MG) + - displayName: Malawi (MW) + required: false + type: String + value: Malawi (MW) + - displayName: Malaysia (MY) + required: false + type: String + value: Malaysia (MY) + - displayName: Maldives (MV) + required: false + type: String + value: Maldives (MV) + - displayName: Mali (ML) + required: false + type: String + value: Mali (ML) + - displayName: Malta (MT) + required: false + type: String + value: Malta (MT) + - displayName: Mauritania (MR) + required: false + type: String + value: Mauritania (MR) + - displayName: Mauritius (MU) + required: false + type: String + value: Mauritius (MU) + - displayName: Mexico (MX) + required: false + type: String + value: Mexico (MX) + - displayName: Moldova (MD) + required: false + type: String + value: Moldova (MD) + - displayName: Monaco (MC) + required: false + type: String + value: Monaco (MC) + - displayName: Mongolia (MN) + required: false + type: String + value: Mongolia (MN) + - displayName: Montenegro (ME) + required: false + type: String + value: Montenegro (ME) + - displayName: Morocco (MA) + required: false + type: String + value: Morocco (MA) + - displayName: Mozambique (MZ) + required: false + type: String + value: Mozambique (MZ) + - displayName: Myanmar (MM) + required: false + type: String + value: Myanmar (MM) + - displayName: Namibia (NA) + required: false + type: String + value: Namibia (NA) + - displayName: Nepal (NP) + required: false + type: String + value: Nepal (NP) + - displayName: Netherlands (NL) + required: false + type: String + value: Netherlands (NL) + - displayName: Netherlands Antilles (AN) + required: false + type: String + value: Netherlands Antilles (AN) + - displayName: New Caledonia (NC) + required: false + type: String + value: New Caledonia (NC) + - displayName: New Zealand (NZ) + required: false + type: String + value: New Zealand (NZ) + - displayName: Nicaragua (NI) + required: false + type: String + value: Nicaragua (NI) + - displayName: Niger (NE) + required: false + type: String + value: Niger (NE) + - displayName: Nigeria (NG) + required: false + type: String + value: Nigeria (NG) + - displayName: North Korea (KP) + required: false + type: String + value: North Korea (KP) + - displayName: Norway (NO) + required: false + type: String + value: Norway (NO) + - displayName: Oman (OM) + required: false + type: String + value: Oman (OM) + - displayName: Pakistan (PK) + required: false + type: String + value: Pakistan (PK) + - displayName: Panama (PA) + required: false + type: String + value: Panama (PA) + - displayName: Papua New Guinea (PG) + required: false + type: String + value: Papua New Guinea (PG) + - displayName: Paraguay (PY) + required: false + type: String + value: Paraguay (PY) + - displayName: Peru (PE) + required: false + type: String + value: Peru (PE) + - displayName: Philippines (PH) + required: false + type: String + value: Philippines (PH) + - displayName: Poland (PL) + required: false + type: String + value: Poland (PL) + - displayName: Portugal (PT) + required: false + type: String + value: Portugal (PT) + - displayName: Puerto Rico (PR) + required: false + type: String + value: Puerto Rico (PR) + - displayName: Qatar (QA) + required: false + type: String + value: Qatar (QA) + - displayName: Romania (RO) + required: false + type: String + value: Romania (RO) + - displayName: Russia (RU) + required: false + type: String + value: Russia (RU) + - displayName: Rwanda (RW) + required: false + type: String + value: Rwanda (RW) + - displayName: Saint Kitts and Nevis (KN) + required: false + type: String + value: Saint Kitts and Nevis (KN) + - displayName: Saint Pierre and Miquelon (PM) + required: false + type: String + value: Saint Pierre and Miquelon (PM) + - displayName: Samoa (WS) + required: false + type: String + value: Samoa (WS) + - displayName: San Marino (SM) + required: false + type: String + value: San Marino (SM) + - displayName: Sao Tome and Principe (ST) + required: false + type: String + value: Sao Tome and Principe (ST) + - displayName: Saudi Arabia (SA) + required: false + type: String + value: Saudi Arabia (SA) + - displayName: Senegal (SN) + required: false + type: String + value: Senegal (SN) + - displayName: Serbia (RS) + required: false + type: String + value: Serbia (RS) + - displayName: Seychelles (SC) + required: false + type: String + value: Seychelles (SC) + - displayName: Sierra Leone (SL) + required: false + type: String + value: Sierra Leone (SL) + - displayName: Singapore (SG) + required: false + type: String + value: Singapore (SG) + - displayName: Slovakia (SK) + required: false + type: String + value: Slovakia (SK) + - displayName: Slovenia (SI) + required: false + type: String + value: Slovenia (SI) + - displayName: Solomon Islands (SB) + required: false + type: String + value: Solomon Islands (SB) + - displayName: Somalia (SO) + required: false + type: String + value: Somalia (SO) + - displayName: South Africa (ZA) + required: false + type: String + value: South Africa (ZA) + - displayName: South Korea (KR) + required: false + type: String + value: South Korea (KR) + - displayName: Spain (ES) + required: false + type: String + value: Spain (ES) + - displayName: Sri Lanka (LK) + required: false + type: String + value: Sri Lanka (LK) + - displayName: St. Lucia (LC) + required: false + type: String + value: St. Lucia (LC) + - displayName: Sudan (SD) + required: false + type: String + value: Sudan (SD) + - displayName: Surinam (SR) + required: false + type: String + value: Surinam (SR) + - displayName: Swaziland (SZ) + required: false + type: String + value: Swaziland (SZ) + - displayName: Sweden (SE) + required: false + type: String + value: Sweden (SE) + - displayName: Switzerland (CH) + required: false + type: String + value: Switzerland (CH) + - displayName: Syria (SY) + required: false + type: String + value: Syria (SY) + - displayName: Taiwan (TW) + required: false + type: String + value: Taiwan (TW) + - displayName: Tajikistan (TJ) + required: false + type: String + value: Tajikistan (TJ) + - displayName: Tanzania (TZ) + required: false + type: String + value: Tanzania (TZ) + - displayName: Thailand (TH) + required: false + type: String + value: Thailand (TH) + - displayName: Togo (TG) + required: false + type: String + value: Togo (TG) + - displayName: Tonga (TO) + required: false + type: String + value: Tonga (TO) + - displayName: Trinidad and Tobago (TT) + required: false + type: String + value: Trinidad and Tobago (TT) + - displayName: Tunisia (TN) + required: false + type: String + value: Tunisia (TN) + - displayName: Turkey (TR) + required: false + type: String + value: Turkey (TR) + - displayName: Turkmenistan (TM) + required: false + type: String + value: Turkmenistan (TM) + - displayName: Tuvalu (TV) + required: false + type: String + value: Tuvalu (TV) + - displayName: Uganda (UG) + required: false + type: String + value: Uganda (UG) + - displayName: Ukraine (UA) + required: false + type: String + value: Ukraine (UA) + - displayName: United Arab Emirates (AE) + required: false + type: String + value: United Arab Emirates (AE) + - displayName: United Kingdom (GB) + required: false + type: String + value: United Kingdom (GB) + - displayName: United States (US) + required: false + type: String + value: United States (US) + - displayName: Uruguay (UY) + required: false + type: String + value: Uruguay (UY) + - displayName: Uzbekistan (UZ) + required: false + type: String + value: Uzbekistan (UZ) + - displayName: Vanuatu (VU) + required: false + type: String + value: Vanuatu (VU) + - displayName: Venezuela (VE) + required: false + type: String + value: Venezuela (VE) + - displayName: Vietnam (VN) + required: false + type: String + value: Vietnam (VN) + - displayName: Virgin Islands U.S. (VI) + required: false + type: String + value: Virgin Islands U.S. (VI) + - displayName: Western Sahara (EH) + required: false + type: String + value: Western Sahara (EH) + - displayName: Yemen (YE) + required: false + type: String + value: Yemen (YE) + - displayName: Zaire (ZR) + required: false + type: String + value: Zaire (ZR) + - displayName: Zambia (ZM) + required: false + type: String + value: Zambia (ZM) + - displayName: Zimbabwe (ZW) + required: false + type: String + value: Zimbabwe (ZW) + required: false + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + validation: + information: [] + warnings: + - details: If you're adding an address for this Supplier, you must also include the first line + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + required: false + type: Array + validation: + information: + - details: Can contain a maximum of one address + field: Addresses + warnings: [] + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + required: true + type: Object + Sage Intacct: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 80 characters + field: Addresses.City + country: + description: The country for the address + displayName: Country + options: + - displayName: United States + required: false + type: String + value: United States + - displayName: Afghanistan + required: false + type: String + value: Afghanistan + - displayName: Aland Islands + required: false + type: String + value: Aland Islands + - displayName: Albania + required: false + type: String + value: Albania + - displayName: Algeria + required: false + type: String + value: Algeria + - displayName: American Samoa + required: false + type: String + value: American Samoa + - displayName: Andorra + required: false + type: String + value: Andorra + - displayName: Angola + required: false + type: String + value: Angola + - displayName: Anguilla + required: false + type: String + value: Anguilla + - displayName: Antarctica + required: false + type: String + value: Antarctica + - displayName: Antigua and Barbuda + required: false + type: String + value: Antigua and Barbuda + - displayName: Argentina + required: false + type: String + value: Argentina + - displayName: Armenia + required: false + type: String + value: Armenia + - displayName: Aruba + required: false + type: String + value: Aruba + - displayName: Australia + required: false + type: String + value: Australia + - displayName: Austria + required: false + type: String + value: Austria + - displayName: Azerbaijan + required: false + type: String + value: Azerbaijan + - displayName: Bahamas + required: false + type: String + value: Bahamas + - displayName: Bahrain + required: false + type: String + value: Bahrain + - displayName: Bangladesh + required: false + type: String + value: Bangladesh + - displayName: Barbados + required: false + type: String + value: Barbados + - displayName: Belarus + required: false + type: String + value: Belarus + - displayName: Belgium + required: false + type: String + value: Belgium + - displayName: Belize + required: false + type: String + value: Belize + - displayName: Benin + required: false + type: String + value: Benin + - displayName: Bermuda + required: false + type: String + value: Bermuda + - displayName: Bhutan + required: false + type: String + value: Bhutan + - displayName: Bolivia + required: false + type: String + value: Bolivia + - displayName: Bonaire, Sint Eustatius and Saba + required: false + type: String + value: Bonaire, Sint Eustatius and Saba + - displayName: Bosnia and Herzegovina + required: false + type: String + value: Bosnia and Herzegovina + - displayName: Botswana + required: false + type: String + value: Botswana + - displayName: Bouvet Island + required: false + type: String + value: Bouvet Island + - displayName: Brazil + required: false + type: String + value: Brazil + - displayName: British Indian Ocean Territory + required: false + type: String + value: British Indian Ocean Territory + - displayName: Brunei Darussalam + required: false + type: String + value: Brunei Darussalam + - displayName: Bulgaria + required: false + type: String + value: Bulgaria + - displayName: Burkina Faso + required: false + type: String + value: Burkina Faso + - displayName: Burundi + required: false + type: String + value: Burundi + - displayName: Cambodia + required: false + type: String + value: Cambodia + - displayName: Cameroon + required: false + type: String + value: Cameroon + - displayName: Canada + required: false + type: String + value: Canada + - displayName: Cape Verde + required: false + type: String + value: Cape Verde + - displayName: Cayman Islands + required: false + type: String + value: Cayman Islands + - displayName: Central African Republic + required: false + type: String + value: Central African Republic + - displayName: Chad + required: false + type: String + value: Chad + - displayName: Chile + required: false + type: String + value: Chile + - displayName: China + required: false + type: String + value: China + - displayName: Christmas Island + required: false + type: String + value: Christmas Island + - displayName: Cocos (Keeling) Islands + required: false + type: String + value: Cocos (Keeling) Islands + - displayName: Colombia + required: false + type: String + value: Colombia + - displayName: Comoros + required: false + type: String + value: Comoros + - displayName: Congo + required: false + type: String + value: Congo + - displayName: Congo, Democratic Republic + required: false + type: String + value: Congo, Democratic Republic + - displayName: Cook Islands + required: false + type: String + value: Cook Islands + - displayName: Costa Rica + required: false + type: String + value: Costa Rica + - displayName: C�te d'Ivoire + required: false + type: String + value: C�te d'Ivoire + - displayName: Croatia + required: false + type: String + value: Croatia + - displayName: Cuba + required: false + type: String + value: Cuba + - displayName: Cura�ao + required: false + type: String + value: Cura�ao + - displayName: Cyprus + required: false + type: String + value: Cyprus + - displayName: Czech Republic + required: false + type: String + value: Czech Republic + - displayName: Denmark + required: false + type: String + value: Denmark + - displayName: Djibouti + required: false + type: String + value: Djibouti + - displayName: Dominica + required: false + type: String + value: Dominica + - displayName: Dominican Republic + required: false + type: String + value: Dominican Republic + - displayName: Ecuador + required: false + type: String + value: Ecuador + - displayName: Egypt + required: false + type: String + value: Egypt + - displayName: El Salvador + required: false + type: String + value: El Salvador + - displayName: Equatorial Guinea + required: false + type: String + value: Equatorial Guinea + - displayName: Eritrea + required: false + type: String + value: Eritrea + - displayName: Estonia + required: false + type: String + value: Estonia + - displayName: Eswatini + required: false + type: String + value: Eswatini + - displayName: Ethiopia + required: false + type: String + value: Ethiopia + - displayName: Falkland Islands (Malvinas + required: false + type: String + value: Falkland Islands (Malvinas + - displayName: Faroe Islands + required: false + type: String + value: Faroe Islands + - displayName: Fiji + required: false + type: String + value: Fiji + - displayName: Finland + required: false + type: String + value: Finland + - displayName: France + required: false + type: String + value: France + - displayName: French Guiana + required: false + type: String + value: French Guiana + - displayName: French Polynesia + required: false + type: String + value: French Polynesia + - displayName: French Southern Territories + required: false + type: String + value: French Southern Territories + - displayName: Gabon + required: false + type: String + value: Gabon + - displayName: Gambia + required: false + type: String + value: Gambia + - displayName: Georgia + required: false + type: String + value: Georgia + - displayName: Germany + required: false + type: String + value: Germany + - displayName: Ghana + required: false + type: String + value: Ghana + - displayName: Gibraltar + required: false + type: String + value: Gibraltar + - displayName: Greece + required: false + type: String + value: Greece + - displayName: Greenland + required: false + type: String + value: Greenland + - displayName: Grenada + required: false + type: String + value: Grenada + - displayName: Guadeloupe + required: false + type: String + value: Guadeloupe + - displayName: Guam + required: false + type: String + value: Guam + - displayName: Guatemala + required: false + type: String + value: Guatemala + - displayName: Guernsey + required: false + type: String + value: Guernsey + - displayName: Guinea + required: false + type: String + value: Guinea + - displayName: Guinea-Bissau + required: false + type: String + value: Guinea-Bissau + - displayName: Guyana + required: false + type: String + value: Guyana + - displayName: Haiti + required: false + type: String + value: Haiti + - displayName: Heard Is. & Mcdonald Islands + required: false + type: String + value: Heard Is. & Mcdonald Islands + - displayName: Honduras + required: false + type: String + value: Honduras + - displayName: Hong Kong + required: false + type: String + value: Hong Kong + - displayName: Hungary + required: false + type: String + value: Hungary + - displayName: Iceland + required: false + type: String + value: Iceland + - displayName: India + required: false + type: String + value: India + - displayName: Indonesia + required: false + type: String + value: Indonesia + - displayName: Iran, Islamic Republic of + required: false + type: String + value: Iran, Islamic Republic of + - displayName: Iraq + required: false + type: String + value: Iraq + - displayName: Ireland + required: false + type: String + value: Ireland + - displayName: Isle of Man + required: false + type: String + value: Isle of Man + - displayName: Israel + required: false + type: String + value: Israel + - displayName: Italy + required: false + type: String + value: Italy + - displayName: Jamaica + required: false + type: String + value: Jamaica + - displayName: Japan + required: false + type: String + value: Japan + - displayName: Jersey + required: false + type: String + value: Jersey + - displayName: Jordan + required: false + type: String + value: Jordan + - displayName: Kazakhstan + required: false + type: String + value: Kazakhstan + - displayName: Kenya + required: false + type: String + value: Kenya + - displayName: Kiribati + required: false + type: String + value: Kiribati + - displayName: Korea, Republic of + required: false + type: String + value: Korea, Republic of + - displayName: Korea, Demo. People's Rep + required: false + type: String + value: Korea, Demo. People's Rep + - displayName: Kosovo + required: false + type: String + value: Kosovo + - displayName: Kuwait + required: false + type: String + value: Kuwait + - displayName: Kyrgyzstan + required: false + type: String + value: Kyrgyzstan + - displayName: Lao + required: false + type: String + value: Lao + - displayName: Latvia + required: false + type: String + value: Latvia + - displayName: Lebanon + required: false + type: String + value: Lebanon + - displayName: Lesotho + required: false + type: String + value: Lesotho + - displayName: Liberia + required: false + type: String + value: Liberia + - displayName: Libyan Arab Jamahiriya + required: false + type: String + value: Libyan Arab Jamahiriya + - displayName: Liechtenstein + required: false + type: String + value: Liechtenstein + - displayName: Lithuania + required: false + type: String + value: Lithuania + - displayName: Luxembourg + required: false + type: String + value: Luxembourg + - displayName: Macao + required: false + type: String + value: Macao + - displayName: Macedonia + required: false + type: String + value: Macedonia + - displayName: Madagascar + required: false + type: String + value: Madagascar + - displayName: Malawi + required: false + type: String + value: Malawi + - displayName: Malaysia + required: false + type: String + value: Malaysia + - displayName: Maldives + required: false + type: String + value: Maldives + - displayName: Mali + required: false + type: String + value: Mali + - displayName: Malta + required: false + type: String + value: Malta + - displayName: Marshall Islands + required: false + type: String + value: Marshall Islands + - displayName: Martinique + required: false + type: String + value: Martinique + - displayName: Mauritania + required: false + type: String + value: Mauritania + - displayName: Mauritius + required: false + type: String + value: Mauritius + - displayName: Mayotte + required: false + type: String + value: Mayotte + - displayName: Mexico + required: false + type: String + value: Mexico + - displayName: Micronesia + required: false + type: String + value: Micronesia + - displayName: Moldova, Republic of + required: false + type: String + value: Moldova, Republic of + - displayName: Monaco + required: false + type: String + value: Monaco + - displayName: Mongolia + required: false + type: String + value: Mongolia + - displayName: Montenegro + required: false + type: String + value: Montenegro + - displayName: Montserrat + required: false + type: String + value: Montserrat + - displayName: Morocco + required: false + type: String + value: Morocco + - displayName: Mozambique + required: false + type: String + value: Mozambique + - displayName: Myanmar + required: false + type: String + value: Myanmar + - displayName: Namibia + required: false + type: String + value: Namibia + - displayName: Nauru + required: false + type: String + value: Nauru + - displayName: Nepal + required: false + type: String + value: Nepal + - displayName: Netherlands + required: false + type: String + value: Netherlands + - displayName: Netherlands Antilles + required: false + type: String + value: Netherlands Antilles + - displayName: New Caledonia + required: false + type: String + value: New Caledonia + - displayName: New Zealand + required: false + type: String + value: New Zealand + - displayName: Nicaragua + required: false + type: String + value: Nicaragua + - displayName: Niger + required: false + type: String + value: Niger + - displayName: Nigeria + required: false + type: String + value: Nigeria + - displayName: Niue + required: false + type: String + value: Niue + - displayName: Norfolk Island + required: false + type: String + value: Norfolk Island + - displayName: Northern Mariana Islands + required: false + type: String + value: Northern Mariana Islands + - displayName: Norway + required: false + type: String + value: Norway + - displayName: Oman + required: false + type: String + value: Oman + - displayName: Pakistan + required: false + type: String + value: Pakistan + - displayName: Palau + required: false + type: String + value: Palau + - displayName: Palestinian Territory, Occupied + required: false + type: String + value: Palestinian Territory, Occupied + - displayName: Panama + required: false + type: String + value: Panama + - displayName: Papua New Guinea + required: false + type: String + value: Papua New Guinea + - displayName: Paraguay + required: false + type: String + value: Paraguay + - displayName: Peru + required: false + type: String + value: Peru + - displayName: Philippines + required: false + type: String + value: Philippines + - displayName: Pitcairn + required: false + type: String + value: Pitcairn + - displayName: Poland + required: false + type: String + value: Poland + - displayName: Portugal + required: false + type: String + value: Portugal + - displayName: Puerto Rico + required: false + type: String + value: Puerto Rico + - displayName: Qatar + required: false + type: String + value: Qatar + - displayName: Reunion + required: false + type: String + value: Reunion + - displayName: Romania + required: false + type: String + value: Romania + - displayName: Russian Federation + required: false + type: String + value: Russian Federation + - displayName: Rwanda + required: false + type: String + value: Rwanda + - displayName: Saint Barthelemy + required: false + type: String + value: Saint Barthelemy + - displayName: Saint Helena + required: false + type: String + value: Saint Helena + - displayName: Saint Kitts and Nevis + required: false + type: String + value: Saint Kitts and Nevis + - displayName: Saint Lucia + required: false + type: String + value: Saint Lucia + - displayName: Saint Martin + required: false + type: String + value: Saint Martin + - displayName: Saint Pierre and Miquelon + required: false + type: String + value: Saint Pierre and Miquelon + - displayName: Saint Vincent and the Grenadines + required: false + type: String + value: Saint Vincent and the Grenadines + - displayName: Samoa + required: false + type: String + value: Samoa + - displayName: San Marino + required: false + type: String + value: San Marino + - displayName: Sao Tome and Principe + required: false + type: String + value: Sao Tome and Principe + - displayName: Saudi Arabia + required: false + type: String + value: Saudi Arabia + - displayName: Senegal + required: false + type: String + value: Senegal + - displayName: Serbia + required: false + type: String + value: Serbia + - displayName: Seychelles + required: false + type: String + value: Seychelles + - displayName: Sierra Leone + required: false + type: String + value: Sierra Leone + - displayName: Singapore + required: false + type: String + value: Singapore + - displayName: Sint Maarten + required: false + type: String + value: Sint Maarten + - displayName: Slovakia + required: false + type: String + value: Slovakia + - displayName: Slovenia + required: false + type: String + value: Slovenia + - displayName: Solomon Islands + required: false + type: String + value: Solomon Islands + - displayName: Somalia + required: false + type: String + value: Somalia + - displayName: South Africa + required: false + type: String + value: South Africa + - displayName: S. Georgia & S. Sandwich Is + required: false + type: String + value: S. Georgia & S. Sandwich Is + - displayName: Spain + required: false + type: String + value: Spain + - displayName: Sri Lanka + required: false + type: String + value: Sri Lanka + - displayName: Sudan + required: false + type: String + value: Sudan + - displayName: South Sudan + required: false + type: String + value: South Sudan + - displayName: Suriname + required: false + type: String + value: Suriname + - displayName: Svalbard and Jan Mayen + required: false + type: String + value: Svalbard and Jan Mayen + - displayName: Sweden + required: false + type: String + value: Sweden + - displayName: Switzerland + required: false + type: String + value: Switzerland + - displayName: Syrian Arab Republic + required: false + type: String + value: Syrian Arab Republic + - displayName: Taiwan + required: false + type: String + value: Taiwan + - displayName: Tajikistan + required: false + type: String + value: Tajikistan + - displayName: Tanzania, United Republic of + required: false + type: String + value: Tanzania, United Republic of + - displayName: Thailand + required: false + type: String + value: Thailand + - displayName: Timor-Leste + required: false + type: String + value: Timor-Leste + - displayName: Togo + required: false + type: String + value: Togo + - displayName: Tokelau + required: false + type: String + value: Tokelau + - displayName: Tonga + required: false + type: String + value: Tonga + - displayName: Trinidad and Tobago + required: false + type: String + value: Trinidad and Tobago + - displayName: Tunisia + required: false + type: String + value: Tunisia + - displayName: Turkey + required: false + type: String + value: Turkey + - displayName: Turkmenistan + required: false + type: String + value: Turkmenistan + - displayName: Turks and Caicos Islands + required: false + type: String + value: Turks and Caicos Islands + - displayName: Tuvalu + required: false + type: String + value: Tuvalu + - displayName: Uganda + required: false + type: String + value: Uganda + - displayName: Ukraine + required: false + type: String + value: Ukraine + - displayName: United Arab Emirates + required: false + type: String + value: United Arab Emirates + - displayName: United Kingdom + required: false + type: String + value: United Kingdom + - displayName: US Minor Outlying Islands + required: false + type: String + value: US Minor Outlying Islands + - displayName: Uruguay + required: false + type: String + value: Uruguay + - displayName: Uzbekistan + required: false + type: String + value: Uzbekistan + - displayName: Vanuatu + required: false + type: String + value: Vanuatu + - displayName: Vatican City State + required: false + type: String + value: Vatican City State + - displayName: Venezuela + required: false + type: String + value: Venezuela + - displayName: Vietnam + required: false + type: String + value: Vietnam + - displayName: Virgin Islands, British + required: false + type: String + value: Virgin Islands, British + - displayName: Virgin Islands, U.S + required: false + type: String + value: Virgin Islands, U.S + - displayName: Wallis and Futuna + required: false + type: String + value: Wallis and Futuna + - displayName: Western Sahara + required: false + type: String + value: Western Sahara + - displayName: Yemen + required: false + type: String + value: Yemen + - displayName: Zambia + required: false + type: String + value: Zambia + - displayName: Zimbabwe + required: false + type: String + value: Zimbabwe + required: false + type: String + validation: + information: [] + warnings: + - details: Required if TaxNumber is supplied + field: Addresses.Country + line1: + description: The first line of the address + displayName: Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: Addresses.Line1 + line2: + description: The second line of the address + displayName: Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: Addresses.Line2 + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 30 characters + field: Addresses.PostalCode + region: + description: The fourth line of the address, or region + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 40 characters + field: Addresses.Region + required: false + type: Array + validation: + information: [] + warnings: + - details: If supplied, must contain only 1 address + field: Addresses + - details: If TaxNumber is supplied, an Address with a Country is required + field: Addresses + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must be between 1 and 200 characters + field: ContactName + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + options: + - displayName: Australian Dollar + required: false + type: String + value: AUD + - displayName: Canadian Dollar + required: false + type: String + value: CAD + - displayName: Pound Sterling + required: false + type: String + value: GBP + - displayName: US Dollar + required: false + type: String + value: USD + - displayName: Rand + required: false + type: String + value: ZAR + required: false + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 200 characters + field: EmailAddress + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 30 characters + field: Phone + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 100 characters + field: RegistrationNumber + status: + description: The current state of the supplier + displayName: Supplier Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Archived + required: false + type: String + value: Archived + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + validation: + information: [] + warnings: + - details: Must be between 1 and 100 characters + field: SupplierName + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: false + type: String + validation: + information: [] + warnings: + - details: Must be no greater than 20 characters + field: TaxNumber + required: true + type: Object + Sandbox: + value: + description: A Supplier is a person or organisation that provides a product or service + displayName: Supplier + properties: + addresses: + description: A collection of addresses associated to the supplier + displayName: Addresses + properties: + city: + description: The third line of the address, or city + displayName: City + required: true + type: String + country: + description: The country for the address + displayName: Country + required: true + type: String + line1: + description: The first line of the address + displayName: Line 1 + required: true + type: String + line2: + description: The second line of the address + displayName: Line 2 + required: true + type: String + postalCode: + description: The postal (or zip) code for the address + displayName: Postal/Zip Code + required: true + type: String + region: + description: The fourth line of the address, or region + displayName: Region + required: true + type: String + type: + description: The type of the address + displayName: Address Type + required: true + type: String + required: true + type: Array + contactName: + description: The name of the main contact for the supplier + displayName: Contact Name + required: true + type: String + defaultCurrency: + description: The default currency for transactions recorded against the supplier + displayName: Default Currency + required: true + type: String + emailAddress: + description: The preferred email address the supplier should be contacted on + displayName: Email Address + required: true + type: String + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + phone: + description: The preferred phone number the supplier should be contacted on + displayName: Phone + required: true + type: String + registrationNumber: + description: The supplier's registration number + displayName: Registration Number + required: true + type: String + status: + description: The current state of the supplier + displayName: Supplier Status + required: true + type: String + supplierName: + description: The name for the supplier, typically a company name + displayName: Supplier Name + required: true + type: String + taxNumber: + description: The supplier's tax number + displayName: Tax Number + required: true + type: String + required: true + type: Object + Xero: + value: + description: An accounts payable contact that supplies good or services, also referred to as a vendor. + displayName: Suppliers + properties: + addresses: + description: Contact addresses for the supplier. + displayName: Addresses + properties: + city: + description: Local city for the address. + displayName: City + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: addresses.city + country: + description: Country for the address. + displayName: Country + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters. + field: addresses.country + line1: + description: First line of the address. + displayName: Address Line 1 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: addresses.line1 + line2: + description: Second line of the address. + displayName: Address Line 2 + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 500 characters. + field: addresses.line2 + postalCode: + description: Post or Zip code for the address. + displayName: Postal code + required: false + type: String + validation: + information: [] + warnings: + - details: Only English alphabet characters are permitted. + field: addresses.postalCode + - details: Max length of 50 characters. + field: addresses.postalCode + region: + description: Region the address is located in. + displayName: Region + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 255 characters. + field: addresses.region + type: + description: The type of address as it related to the supplier. + displayName: Type + options: + - displayName: Billing Address + required: false + type: String + value: Billing + - displayName: Delivery Address + required: false + type: String + value: Delivery + required: true + type: String + validation: + information: [] + warnings: + - details: Billing = POBOX, Delivery/Unknown = DELIVERY + field: addresses.type + required: false + type: Array + emailAddress: + description: Main contact email for the supplier. + displayName: Email + required: false + type: String + phone: + description: Main contact phone number for the supplier. + displayName: Phone + required: false + type: String + validation: + information: [] + warnings: + - details: Country, area, and number are space separated + field: phone + registrationNumber: + description: Legal company registration identifier. + displayName: Registration Number + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 50 characters + field: registrationNumber + status: + description: Status of the supplier account. + displayName: Status + options: + - displayName: Active + required: false + type: String + value: Active + - displayName: Inactive + required: false + type: String + value: InActive + required: false + type: String + supplierName: + description: Name of the supplier. + displayName: Name + required: true + type: String + taxNumber: + description: Legal tax registration identifier. + displayName: Tax Number + required: false + type: String + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create/update supplier model + tags: + - Suppliers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/options/transfers": + get: + description: |- + Get create transfer model. Returns the expected data for the request payload. + + See the examples for integration-specific indicative models. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=transfers) for integrations that support creating transfers. + operationId: get-create-transfers-model + responses: + "200": + content: + application/json: + examples: + Exact (Netherlands): + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + contactRef: + description: The customer or supplier for this transfer if known + displayName: Contact Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: customers + required: false + type: String + value: customers + - displayName: suppliers + required: false + type: String + value: suppliers + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer or supplier. + field: ContactRef.Id + required: false + type: Object + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: chartOfAccounts + required: false + type: String + value: chartOfAccounts + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank or nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Transfers between two bank accounts must be handled with two separate transfers to/from an offset account (only balance sheet type nominal account). + field: From.AccountRef + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Transfer Amount must be greater than zero. + field: From.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: chartOfAccounts + required: false + type: String + value: chartOfAccounts + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank or nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Transfers between two bank accounts must be handled with two separate transfers to/from an offset account (only balance sheet type nominal account). + field: To.AccountRef + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Transfer Amount must be greater than zero. + field: To.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this transfer is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: false + type: String + required: false + type: Array + required: true + type: Object + Exact (UK): + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + contactRef: + description: The customer or supplier for this transfer if known + displayName: Contact Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: customers + required: false + type: String + value: customers + - displayName: suppliers + required: false + type: String + value: suppliers + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing customer or supplier. + field: ContactRef.Id + required: false + type: Object + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: chartOfAccounts + required: false + type: String + value: chartOfAccounts + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank or nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Transfers between two bank accounts must be handled with two separate transfers to/from an offset account (only balance sheet type nominal account). + field: From.AccountRef + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Transfer Amount must be greater than zero. + field: From.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: chartOfAccounts + required: false + type: String + value: chartOfAccounts + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank or nominal account. + field: AccountRef.Id + required: true + type: Object + validation: + information: [] + warnings: + - details: Transfers between two bank accounts must be handled with two separate transfers to/from an offset account (only balance sheet type nominal account). + field: To.AccountRef + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Transfer Amount must be greater than zero. + field: To.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this transfer is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: false + type: String + required: false + type: Array + required: true + type: Object + FreeAgent: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be provided and be greater than zero. + field: From.Amount + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: false + type: Number + validation: + information: [] + warnings: + - details: If provided, must be greater than zero. + field: To.Amount + - details: It will be taken into account just if the accounts are in different currencies and will override the automatic currency conversion. + field: To.Amount + required: true + type: Object + required: true + type: Object + Oracle NetSuite: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + date: + description: The date the transfer occurred + displayName: Transfer Date + required: false + type: DateTime + validation: + information: + - details: Will default to today's date if not provided + field: Date + warnings: [] + depositedRecordRefs: + description: A collection of selected transactions to associate with the transfer. Use this field to include transactions which are posted to the undeposited funds (or other holding) account within this transfer. + displayName: Deposited Record References + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Array + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Either the 'From' account or the 'To' account must be a bank account - the other must be an undeposited funds account + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Either the 'From' account or the 'To' account must be a bank account - the other must be an undeposited funds account + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this transfer is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: One location, one department and one classification may be provided + field: TrackingCategoryRefs.Id + required: false + type: Array + required: true + type: Object + validation: + information: [] + warnings: + - details: Currently only transfers between bank accounts and undeposited funds accounts are supported + QuickBooks Desktop: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + contactRef: + description: The customer or supplier for this transfer if known + displayName: Contact Reference + required: false + type: Object + validation: + information: [] + warnings: + - details: This value is not used in the push, and will be ignored. + field: ContactRef + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + validation: + information: [] + warnings: + - details: Max length of 4096 characters. + field: Description + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Value should match To.Amount + field: From.Amount + - details: Value should be greater than zero + field: From.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: This value is not used in the push, and will be ignored. + field: From.Currency + required: true + type: Object + sourceModifiedDate: + description: The date the record was last changed in the originating system + displayName: Source Modified Date + required: true + type: DateTime + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Value should match To.Amount + field: To.Amount + - details: Value should be greater than zero + field: To.Amount + currency: + description: The currency of the transfer + displayName: Currency + required: false + type: String + validation: + information: [] + warnings: + - details: This value is not used in the push, and will be ignored. + field: To.Currency + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this transfer is being tracked against + displayName: Tracking Category References + required: false + type: Array + required: true + type: Object + QuickBooks Online: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + depositedRecordRefs: + description: A collection of selected transactions to associate with the transfer. Use this field to include transactions which are posted to the undeposited funds (or other holding) account within this transfer. + displayName: Deposited Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: Payments + required: false + type: String + value: payments + - displayName: DirectIncomes + required: false + type: String + value: directIncomes + - displayName: JournalEntries + required: false + type: String + value: journalEntries + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: false + type: Array + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + required: true + type: Object + validation: + information: [] + warnings: + - details: When pushing a transfer using two different currencies, the exchange rate will be calculated and passed to QuickBooks, QuickBooks performs rounding on this value which may affect the values in the transfer + - details: Transfers between accounts in different currencies can only be made if multi-currency is enabled for company + - details: The currency of at least one of the accounts used must be the same as the company's currency + QuickBooks Online Sandbox: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + depositedRecordRefs: + description: A collection of selected transactions to associate with the transfer. Use this field to include transactions which are posted to the undeposited funds (or other holding) account within this transfer. + displayName: Deposited Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + options: + - displayName: Payments + required: false + type: String + value: payments + - displayName: DirectIncomes + required: false + type: String + value: directIncomes + - displayName: JournalEntries + required: false + type: String + value: journalEntries + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: false + type: Array + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + required: true + type: Object + required: true + type: Object + validation: + information: [] + warnings: + - details: When pushing a transfer using two different currencies, the exchange rate will be calculated and passed to QuickBooks, QuickBooks performs rounding on this value which may affect the values in the transfer + - details: Transfers between accounts in different currencies can only be made if multi-currency is enabled for company + - details: The currency of at least one of the accounts used must be the same as the company's currency + Sage Business Cloud Accounting: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + validation: + information: + - details: Must be provided. + field: Date + warnings: [] + description: + description: The description of the transfer + displayName: Transfer Description + required: false + type: String + validation: + information: + - details: Must not be longer than 2000 characters. + field: Description + warnings: + - details: Must be provided if pushing a bank deposit. + field: Description + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be different from To.AccountRef.Id. + field: AccountRef.Id + - details: Must match the ID of an existing bank account in the company's base currency. + field: AccountRef.Id + warnings: [] + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be equal to To.Amount. + field: From.Amount + - details: Must be greater than zero. + field: From.Amount + warnings: [] + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: + - details: Must be different from From.AccountRef.Id. + field: AccountRef.Id + - details: Must match the ID of an existing bank account in the company's base currency. + field: AccountRef.Id + warnings: [] + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: + - details: Must be equal to From.Amount. + field: To.Amount + - details: Must be greater than zero. + field: To.Amount + warnings: [] + required: true + type: Object + required: true + type: Object + Sandbox: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + contactRef: + description: The customer or supplier for this transfer if known + displayName: Contact Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + depositedRecordRefs: + description: A collection of selected transactions to associate with the transfer. Use this field to include transactions which are posted to the undeposited funds (or other holding) account within this transfer. + displayName: Deposited Record References + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Array + description: + description: The description of the transfer + displayName: Transfer Description + required: true + type: String + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + currency: + description: The currency of the transfer + displayName: Currency + required: true + type: String + status: + description: The status of the transfer in the account + displayName: Status + required: true + type: String + required: true + type: Object + metadata: + description: Miscellaneous data about the item + displayName: Metadata + properties: + isDeleted: + description: A boolean to indicate whether the object has been deleted + displayName: IsDeleted + required: true + type: Boolean + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + dataType: + description: The name of the data type for which the ID is valid. + displayName: DataType + required: true + type: String + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + currency: + description: The currency of the transfer + displayName: Currency + required: true + type: String + status: + description: The status of the transfer in the account + displayName: Status + required: true + type: String + required: true + type: Object + trackingCategoryRefs: + description: A collection of categories this transfer is being tracked against + displayName: Tracking Category References + properties: + id: + description: The identifier for the item, unique per tracking category + displayName: Identifier + required: true + type: String + name: + description: The name of the category referenced by the identifier + displayName: Tracking Category Name + required: true + type: String + required: true + type: Array + required: true + type: Object + Xero: + value: + description: Transfers to or from a bank account + displayName: Transfer + properties: + date: + description: The date the transfer occurred + displayName: Transfer Date + required: true + type: DateTime + from: + description: The account and amount that money was transfered from + displayName: Transfered From + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be equal to To.Amount. + field: From.Amount + - details: Must be greater than zero. + field: From.Amount + status: + description: The status of the transfer in the account + displayName: Status + options: + - displayName: Unknown + required: false + type: String + value: Unknown + - displayName: Unreconciled + required: false + type: String + value: Unreconciled + - displayName: Reconciled + required: false + type: String + value: Reconciled + required: true + type: String + validation: + information: + - details: Must be provided. + field: From.Status + warnings: [] + required: true + type: Object + to: + description: The account and amount that money was transfered to + displayName: Transfered To + properties: + accountRef: + description: Reference to the bank or nominal account + displayName: Account Reference + properties: + id: + description: The reference identifier for the record + displayName: Identifier + required: true + type: String + validation: + information: [] + warnings: + - details: Must match the ID of an existing bank account. + field: AccountRef.Id + required: true + type: Object + amount: + description: The amount transfered + displayName: Amount + required: true + type: Number + validation: + information: [] + warnings: + - details: Must be equal to From.Amount. + field: To.Amount + - details: Must be greater than zero. + field: To.Amount + status: + description: The status of the transfer in the account + displayName: Status + options: + - displayName: Unknown + required: false + type: String + value: Unknown + - displayName: Unreconciled + required: false + type: String + value: Unreconciled + - displayName: Reconciled + required: false + type: String + value: Reconciled + required: true + type: String + validation: + information: + - details: Must be provided. + field: To.Status + warnings: [] + required: true + type: Object + required: true + type: Object + schema: + $ref: "#/components/schemas/PushOption" + description: OK + summary: Get create transfer model + tags: + - Transfers + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/push/accounts": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Creates a new account for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create account model](https://docs.codat.io/accounting-api#/operations/get-create-chartOfAccounts-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=chartOfAccounts) for integrations that support creating an account. + operationId: create-account + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Account" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateAccountResponse" + description: Success + summary: Create account + tags: + - Accounts + "/companies/{companyId}/connections/{connectionId}/push/bankAccounts": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new bank account to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [](). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bankAccounts) for integrations that support creating bank accounts. + operationId: create-bank-account + parameters: + - $ref: "#/components/parameters/allowSyncOnPushComplete" + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankAccount" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBankAccountResponse" + description: Success + summary: Create bank account + tags: + - Bank accounts + "/companies/{companyId}/connections/{connectionId}/push/bankAccounts/{accountId}/bankTransactions": + post: + description: |- + Posts bank transactions to the accounting package for a given company. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bankTransactions) for integrations that support POST methods. + operationId: create-bank-transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/paths/~1companies~1%7BcompanyId%7D~1connections~1%7BconnectionId%7D~1data~1bankAccounts~1%7BaccountId%7D~1bankTransactions/get/parameters/2" + - $ref: "#/components/parameters/allowSyncOnPushComplete" + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankTransactions" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBankTransactionsResponse" + description: Success + summary: Create bank transactions + tags: + - Bank account transactions + "/companies/{companyId}/connections/{connectionId}/push/bankAccounts/{bankAccountId}": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/bankAccountId" + put: + description: |- + Posts an updated bank account to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [](). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bankAccounts) for integrations that support updating bank accounts. + operationId: update-bank-account + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankAccount" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateBankAccountResponse" + description: Success + summary: Update bank account + tags: + - Bank accounts + "/companies/{companyId}/connections/{connectionId}/push/billCreditNotes": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new billCreditNote to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update bill credit note model](https://docs.codat.io/accounting-api#/operations/get-create-update-billCreditNotes-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=billCreditNotes) for integrations that support creating bill credit notes. + operationId: create-bill-credit-note + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BillCreditNote" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBillCreditNoteResponse" + description: Success + summary: Create bill credit note + tags: + - Bill credit notes + "/companies/{companyId}/connections/{connectionId}/push/billCreditNotes/{billCreditNoteId}": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: billCreditNoteId + required: true + schema: + type: string + put: + description: |- + Posts an updated billCreditNote to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update bill credit note model](https://docs.codat.io/accounting-api#/operations/get-create-update-billCreditNotes-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=billCreditNotes) for integrations that support updating bill credit notes. + operationId: update-bill-credit-note + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BillCreditNote" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateBillCreditNoteResponse" + description: Success + summary: Update bill credit note + tags: + - Bill credit notes + "/companies/{companyId}/connections/{connectionId}/push/billPayments": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new bill payment to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create bill payment model](https://docs.codat.io/accounting-api#/operations/get-create-billPayments-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=billPayments) for integrations that support creating bill payments. + operationId: create-bill-payment + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BillPayment" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBillPaymentResponse" + description: Success + summary: Create bill payments + tags: + - Bill payments + "/companies/{companyId}/connections/{connectionId}/push/billPayments/{billPaymentId}": + delete: + description: |- + Deletes a bill payment from the accounting package for a given company. + + > **Supported Integrations** + > + > This functionality is currently only supported for our Oracle NetSuite integration. Check out our [public roadmap](https://portal.productboard.com/codat/7-public-product-roadmap/tabs/46-accounting-api) to see what we're building next, and to submit ideas for new features. + operationId: delete-billPayment + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOperationSummary" + description: OK + summary: Delete bill payment + tags: + - Bill payments + parameters: + - in: path + name: companyId + required: true + schema: + type: string + - in: path + name: connectionId + required: true + schema: + type: string + - in: path + name: billPaymentId + required: true + schema: + type: string + "/companies/{companyId}/connections/{connectionId}/push/bills": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new bill to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update bill model](https://docs.codat.io/accounting-api#/operations/get-create-update-bills-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bills) for integrations that support creating a bill. + operationId: create-bill + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Bill" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBillResponse" + description: Success + summary: Create bill + tags: + - Bills + "/companies/{companyId}/connections/{connectionId}/push/bills/{billId}": + delete: + description: |- + Deletes a bill from the accounting package for a given company. + + > **Supported Integrations** + > + > This functionality is currently only supported for our Oracle NetSuite and QuickBooks Online integrations. Check out our [public roadmap](https://portal.productboard.com/codat/7-public-product-roadmap/tabs/46-accounting-api) to see what we're building next, and to submit ideas for new features. + operationId: delete-bill + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOperationSummary" + description: OK + headers: {} + summary: Delete bill + tags: + - Bills + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + put: + description: |- + Posts an updated bill to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update bill model](https://docs.codat.io/accounting-api#/operations/get-create-update-bills-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bills) for integrations that support updating a bill. + operationId: update-bill + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Bill" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateBillResponse" + description: Success + summary: Update bill + tags: + - Bills + "/companies/{companyId}/connections/{connectionId}/push/bills/{billId}/attachments": + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: Upload bill attachments + operationId: upload-bill-attachments + requestBody: + content: + multipart/form-data: + schema: {} + responses: + "200": + description: Success + summary: Upload bill attachments + tags: + - Bills + "/companies/{companyId}/connections/{connectionId}/push/creditNotes": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Push credit note + + + Required data may vary by integration. To see what data to post, first call [Get create/update credit note model](https://docs.codat.io/accounting-api#/operations/get-create-update-creditNotes-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=creditNotes) for integrations that support creating a credit note. + operationId: create-credit-note + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/CreditNote" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCreditNoteResponse" + description: Success + summary: Create credit note + tags: + - Credit notes + "/companies/{companyId}/connections/{connectionId}/push/creditNotes/{creditNoteId}": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: creditNoteId + required: true + schema: + type: string + put: + description: |- + Posts an updated credit note to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update credit note model](https://docs.codat.io/accounting-api#/operations/get-create-update-creditNotes-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=creditNotes) for integrations that support updating a credit note. + operationId: update-credit-note + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/CreditNote" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateCreditNoteResponse" + description: Success + summary: Update creditNote + tags: + - Credit notes + "/companies/{companyId}/connections/{connectionId}/push/customers": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts an individual customer for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/accounting-api#/operations/get-create-update-customers-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=customers) for integrations that support creating customers. + operationId: create-customer + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Customer" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCustomerResponse" + description: Success + summary: Create customer + tags: + - Customers + "/companies/{companyId}/connections/{connectionId}/push/customers/{customerId}": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: customerId + required: true + schema: + type: string + put: + description: |- + Posts an updated customer for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/accounting-api#/operations/get-create-update-customers-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=customers) for integrations that support updating customers. + operationId: update-customer + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Customer" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateCustomerResponse" + description: Success + summary: Update customer + tags: + - Customers + "/companies/{companyId}/connections/{connectionId}/push/directCosts": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new direct cost to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create direct cost model](https://docs.codat.io/accounting-api#/operations/get-create-directCosts-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=directCosts) for integrations that support creating direct costs. + operationId: create-direct-cost + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DirectCost" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateDirectCostResponse" + description: Success + summary: Create direct cost + tags: + - Direct costs + "/companies/{companyId}/connections/{connectionId}/push/directCosts/{directCostId}/attachment": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/directCostId" + post: + description: Posts a new direct cost attachment for a given company. + operationId: upload-direct-cost-attachment + requestBody: + content: + multipart/form-data: + schema: {} + responses: + "200": + description: Success + summary: Upload direct cost attachment + tags: + - Direct costs + "/companies/{companyId}/connections/{connectionId}/push/directIncomes": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new direct income to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create direct income model](https://docs.codat.io/accounting-api#/operations/get-create-directIncomes-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=directIncomes) for integrations that support creating direct incomes. + operationId: create-direct-income + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DirectIncome" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateDirectIncomeResponse" + description: Success + summary: Create direct income + tags: + - Direct incomes + "/companies/{companyId}/connections/{connectionId}/push/directIncomes/{directIncomeId}/attachment": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: Posts a new direct income attachment for a given company. + operationId: upload-direct-income-attachment + parameters: + - in: path + name: directIncomeId + required: true + schema: + type: string + requestBody: + content: + multipart/form-data: + schema: {} + responses: + "200": + description: Success + summary: Create direct income attachment + tags: + - Direct incomes + "/companies/{companyId}/connections/{connectionId}/push/invoices": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new invoice to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update invoice model](https://docs.codat.io/accounting-api#/operations/get-create-update-invoices-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=invoices) for integrations that support creating invoices. + operationId: create-invoice + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Invoice" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateInvoiceResponse" + description: Success + summary: Create invoice + tags: + - Invoices + "/companies/{companyId}/connections/{connectionId}/push/invoices/{invoiceId}": + delete: + description: |- + Deletes an invoice from the accounting package for a given company. + + > **Supported Integrations** + > + > This functionality is currently only supported for our QuickBooks Online integration. Check out our [public roadmap](https://portal.productboard.com/codat/7-public-product-roadmap/tabs/46-accounting-api) to see what we're building next, and to submit ideas for new features. + operationId: delete-invoice + parameters: + - $ref: "#/components/parameters/invoiceId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOperationSummary" + description: OK + headers: {} + summary: Delete invoice + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + put: + description: |- + Posts an updated invoice to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update invoice model](https://docs.codat.io/accounting-api#/operations/get-create-update-invoices-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=invoices) for integrations that support updating invoices. + operationId: update-invoice + parameters: + - $ref: "#/components/parameters/invoiceId" + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Invoice" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateInvoiceResponse" + description: Success + summary: Update invoice + tags: + - Invoices + "/companies/{companyId}/connections/{connectionId}/push/invoices/{invoiceId}/attachment": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: Push invoice attachment + operationId: upload-invoice-attachment + parameters: + - $ref: "#/components/parameters/invoiceId" + requestBody: + content: + multipart/form-data: + schema: {} + responses: + "200": + description: Success + summary: Push invoice attachment + tags: + - Invoices + "/companies/{companyId}/connections/{connectionId}/push/items": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new item to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create item model](https://docs.codat.io/accounting-api#/operations/get-create-items-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=items) for integrations that support creating items. + operationId: create-item + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Item" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateItemResponse" + description: Success + summary: Create item + tags: + - Items + "/companies/{companyId}/connections/{connectionId}/push/journalEntries": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new journalEntry to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create journal entry model](https://docs.codat.io/accounting-api#/operations/get-create-journalEntries-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=journalEntries) for integrations that support creating journal entries. + operationId: create-journal-entry + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/JournalEntry" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateJournalEntryResponse" + description: Success + summary: Create journal entry + tags: + - Journal entries + "/companies/{companyId}/connections/{connectionId}/push/journalEntries/{journalEntryId}": + delete: + description: |- + Deletes a journal entry from the accounting package for a given company. + + > **Supported Integrations** + > + > This functionality is currently only supported for our QuickBooks Online integration. Check out our [public roadmap](https://portal.productboard.com/codat/7-public-product-roadmap/tabs/46-accounting-api) to see what we're building next, and to submit ideas for new features. + operationId: delete-journal-entry + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOperationSummary" + description: OK + headers: {} + summary: Delete journal entry + tags: + - Journal entries + parameters: + - $ref: "#/components/parameters/journalEntryId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + "/companies/{companyId}/connections/{connectionId}/push/journals": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new journal to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create journal model](https://docs.codat.io/accounting-api#/operations/get-create-journals-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=journals) for integrations that support creating journals. + operationId: push-journal + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Journal" + responses: + "200": + content: + application/json: + schema: + allOf: + - properties: + data: + $ref: "#/components/schemas/Journal" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + description: Success + summary: Create journal + tags: + - Journals + "/companies/{companyId}/connections/{connectionId}/push/payments": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new payment to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create payment model](https://docs.codat.io/accounting-api#/operations/get-create-payments-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=payments) for integrations that support creating payments. + operationId: create-payment + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Payment" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreatePaymentResponse" + description: Success + summary: Create payment + tags: + - Payments + "/companies/{companyId}/connections/{connectionId}/push/purchaseOrders": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new purchase order to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create/update purchase order model](https://docs.codat.io/accounting-api#/operations/get-create-update-purchaseOrders-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=purchaseOrders) for integrations that support creating purchase orders. + operationId: create-purchase-order + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PurchaseOrder" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreatePurchaseOrderResponse" + description: Success + summary: Create purchase order + tags: + - Purchase orders + "/companies/{companyId}/connections/{connectionId}/push/purchaseOrders/{purchaseOrderId}": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - in: path + name: purchaseOrderId + required: true + schema: + type: string + put: + description: |- + Posts an updated purchase order to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [](). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=purchaseOrders) for integrations that support updating purchase orders. + operationId: update-purchase-order + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PurchaseOrder" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/UpdatePurchaseOrderResponse" + description: Success + summary: Update purchase order + tags: + - Purchase orders + "/companies/{companyId}/connections/{connectionId}/push/suppliers": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Push suppliers + + Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/accounting-api#/operations/get-create-update-suppliers-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=suppliers) for integrations that support creating suppliers. + operationId: create-supplier + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Supplier" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSupplierResponse" + description: Success + summary: Create suppliers + tags: + - Suppliers + "/companies/{companyId}/connections/{connectionId}/push/suppliers/{supplierId}": + parameters: + - $ref: "#/components/parameters/supplierId" + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + put: + description: |- + Push supplier + + Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/accounting-api#/operations/get-create-update-suppliers-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=suppliers) for integrations that support updating suppliers. + operationId: put-supplier + parameters: + - $ref: "#/components/parameters/timeoutInMinutes" + - $ref: "#/components/parameters/forceUpdate" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Supplier" + responses: + "200": + content: + application/json: + schema: + allOf: + - properties: + data: + $ref: "#/components/schemas/Supplier" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + description: Success + summary: Update supplier + tags: + - Suppliers + "/companies/{companyId}/connections/{connectionId}/push/transfers": + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + post: + description: |- + Posts a new transfer to the accounting package for a given company. + + Required data may vary by integration. To see what data to post, first call [Get create transfer model](https://docs.codat.io/accounting-api#/operations/get-create-transfers-model). + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=transfers) for integrations that support creating transfers. + operationId: create-transfer + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Transfer" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateTransferResponse" + description: Success + summary: Create transfer + tags: + - Transfers + "/companies/{companyId}/data/accounts": + get: + description: Gets the latest accounts for a company + operationId: list-accounts + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Accounts" + x-speakeasy-usage-example: true + description: Success + summary: List accounts + tags: + - Accounts + "/companies/{companyId}/data/accounts/{accountId}": + get: + deprecated: true + description: Gets a single account corresponding to the given ID. + operationId: get-account + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Account" + description: Success + summary: Get account + tags: + - Accounts + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/accountId" + "/companies/{companyId}/data/bankAccounts/{accountId}": + get: + deprecated: true + description: Gets the bank account for given account ID. + operationId: get-all-bank-account + parameters: + - $ref: "#/components/parameters/query" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankStatementAccount" + description: Success + summary: Get bank account + tags: + - Bank accounts + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/accountId" + "/companies/{companyId}/data/bankAccounts/{accountId}/transactions": + get: + description: Gets the latest bank transactions for given account ID and company. Doesn't require connection ID. + operationId: list-bank-transactions + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankAccountTransactions" + description: Success + summary: List all bank transactions + tags: + - Bank account transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/accountId" + "/companies/{companyId}/data/billCreditNotes": + get: + description: Gets a list of all bill credit notes for a company, with pagination + operationId: list-bill-credit-notes + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BillCreditNotes" + description: Success + summary: List bill credit notes + tags: + - Bill credit notes + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/billCreditNotes/{billCreditNoteId}": + get: + deprecated: true + description: Gets a single billCreditNote corresponding to the given ID. + operationId: get-bill-credit-note + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BillCreditNote" + description: Success + summary: Get bill credit note + tags: + - Bill credit notes + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: billCreditNoteId + required: true + schema: + type: string + "/companies/{companyId}/data/billPayments": + get: + description: Gets the latest billPayments for a company, with pagination + operationId: list-bill-payments + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BillPayments" + description: Success + summary: List bill payments + tags: + - Bill payments + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/billPayments/{billPaymentId}": + get: + deprecated: true + description: Get a bill payment + operationId: get-bill-payments + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BillPayment" + description: Success + summary: Get bill payment + tags: + - Bill payments + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: billPaymentId + required: true + schema: + type: string + "/companies/{companyId}/data/bills": + get: + description: Gets the latest bills for a company, with pagination + operationId: list-bills + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Bills" + description: Success + summary: List bills + tags: + - Bills + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/bills/{billId}": + get: + description: Get bill + operationId: get-bill + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Bill" + description: Success + summary: Get bill + tags: + - Bills + parameters: + - $ref: "#/components/parameters/billId" + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/creditNotes": + get: + description: Gets a list of all credit notes for a company, with pagination + operationId: list-credit-notes + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreditNotes" + description: Success + summary: List credit notes + tags: + - Credit notes + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/creditNotes/{creditNoteId}": + get: + deprecated: true + description: Gets a single creditNote corresponding to the given ID. + operationId: get-credit-note + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreditNote" + description: Success + summary: Get credit note + tags: + - Credit notes + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: creditNoteId + required: true + schema: + type: string + "/companies/{companyId}/data/customers": + get: + description: Gets the latest customers for a company, with pagination + operationId: get-customers + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Customers" + description: Success + summary: List customers + tags: + - Customers + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/customers/{customerId}": + get: + deprecated: true + description: Gets a single customer corresponding to the given ID. + operationId: get-customer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Customer" + description: Success + summary: Get customer + tags: + - Customers + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: customerId + required: true + schema: + type: string + "/companies/{companyId}/data/financials/balanceSheet": + get: + description: Gets the latest balance sheet for a company. + operationId: get-balance-sheet + parameters: + - $ref: "#/components/parameters/periodLength" + - $ref: "#/components/parameters/periodsToCompare" + - $ref: "#/components/parameters/startMonth" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BalanceSheet" + description: Success + summary: Get balance sheet + tags: + - Financials + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/financials/cashFlowStatement": + get: + description: Gets the latest cash flow statement for a company. + operationId: get-cash-flow-statement + parameters: + - $ref: "#/components/parameters/periodLength" + - $ref: "#/components/parameters/periodsToCompare" + - $ref: "#/components/parameters/startMonth" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CashFlowStatement" + description: Success + summary: Get cash flow statement + tags: + - Financials + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/financials/profitAndLoss": + get: + description: Gets the latest profit and loss for a company. + operationId: get-profit-and-loss + parameters: + - $ref: "#/components/parameters/periodLength" + - $ref: "#/components/parameters/periodsToCompare" + - $ref: "#/components/parameters/startMonth" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProfitAndLossReport" + description: Success + summary: Get profit and loss + tags: + - Financials + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/info": + get: + description: Gets the latest basic info for a company. + operationId: get-company-info + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CompanyDataset" + description: Success + summary: Get company info + tags: + - Company info + parameters: + - $ref: "#/components/parameters/companyId" + post: + description: Initiates the process of synchronising basic info for a company + operationId: post-sync-info + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Dataset" + description: Success + summary: Refresh company info + tags: + - Company info + "/companies/{companyId}/data/invoices": + get: + description: Gets the latest invoices for a company, with pagination + operationId: list-invoices + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Invoices" + description: Success + summary: List invoices + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/invoices/{invoiceId}": + get: + deprecated: true + description: Get invoice + operationId: get-invoice + parameters: + - $ref: "#/components/parameters/invoiceId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Invoice" + description: Success + summary: Get invoice + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/invoices/{invoiceId}/pdf": + get: + description: Get invoice as PDF + operationId: Download-invoice-pdf + parameters: + - $ref: "#/components/parameters/invoiceId" + responses: + "200": + content: + application/octet-stream: + schema: + title: Data + description: Success + summary: Get invoice as PDF + tags: + - Invoices + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/items": + get: + description: Gets the items for a given company. + operationId: list-items + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Items" + description: Success + summary: List items + tags: + - Items + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/items/{itemId}": + get: + deprecated: true + description: Gets the specified item for a given company. + operationId: get-item + parameters: + - in: path + name: itemId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Item" + description: Success + summary: Get item + tags: + - Items + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/journalEntries": + get: + description: Gets the latest journal entries for a company, with pagination + operationId: list-journal-entries + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/JournalEntries" + description: Success + summary: List journal entries + tags: + - Journal entries + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/journalEntries/{journalEntryId}": + get: + deprecated: true + description: Gets a single JournalEntry corresponding to the given ID. + operationId: get-journal-entry + parameters: + - in: path + name: journalEntryId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/JournalEntry" + description: Success + summary: Get journal entry + tags: + - Journal entries + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/journals": + get: + description: Gets the latest journals for a company, with pagination + operationId: list-journals + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Journals" + description: Success + summary: List journals + tags: + - Journals + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/journals/{journalId}": + get: + deprecated: true + description: Gets a single journal corresponding to the given ID. + operationId: get-journal + parameters: + - in: path + name: journalId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Journal" + description: Success + summary: Get journal + tags: + - Journals + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/paymentMethods": + get: + deprecated: true + description: Gets the payment methods for a given company. + operationId: list-payment-methods + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethods" + description: Success + summary: List all payment methods + tags: + - Payment methods + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/paymentMethods/{paymentMethodId}": + get: + deprecated: true + description: Gets the specified payment method for a given company. + operationId: get-payment-method + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PaymentMethod" + description: Success + summary: Get payment method + tags: + - Payment methods + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: paymentMethodId + required: true + schema: + type: string + "/companies/{companyId}/data/payments": + get: + description: Gets the latest payments for a company, with pagination + operationId: list-payments + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Payments" + description: Success + summary: List payments + tags: + - Payments + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/payments/{paymentId}": + get: + deprecated: true + description: Get payment + operationId: get-payment + parameters: + - in: path + name: paymentId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Payment" + description: Success + summary: Get payment + tags: + - Payments + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/purchaseOrders": + get: + description: Get purchase orders + operationId: list-purchase-orders + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PurchaseOrders" + description: Success + summary: List purchase orders + tags: + - Purchase orders + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/purchaseOrders/{purchaseOrderId}": + get: + deprecated: true + description: Get purchase order + operationId: get-purchase-order + parameters: + - in: path + name: purchaseOrderId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PurchaseOrder" + description: Success + summary: Get purchase order + tags: + - Purchase orders + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/salesOrders": + get: + description: Get sales orders + operationId: list-sales-orders + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SalesOrders" + description: Success + summary: List sales orders + tags: + - Sales orders + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/salesOrders/{salesOrderId}": + get: + deprecated: true + description: Get sales order + operationId: get-sales-order + parameters: + - in: path + name: salesOrderId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SalesOrder" + description: Success + summary: Get sales order + tags: + - Sales orders + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/suppliers": + get: + description: Gets the latest suppliers for a company, with pagination + operationId: list-suppliers + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Suppliers" + description: Success + summary: List suppliers + tags: + - Suppliers + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/suppliers/{supplierId}": + get: + deprecated: true + description: Gets a single supplier corresponding to the given ID. + operationId: get-supplier + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Supplier" + description: Success + summary: Get supplier + tags: + - Suppliers + x-internal: true + parameters: + - $ref: "#/components/parameters/supplierId" + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/taxRates": + get: + description: Gets the latest tax rates for a given company. + operationId: list-tax-rates + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TaxRates" + description: Success + summary: List all tax rates + tags: + - Tax rates + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/taxRates/{taxRateId}": + get: + deprecated: true + description: Gets the specified tax rate for a given company. + operationId: get-tax-rate + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TaxRate" + description: Success + summary: Get tax rate + tags: + - Tax rates + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: taxRateId + required: true + schema: + type: string + "/companies/{companyId}/data/trackingCategories": + get: + description: Gets the latest tracking categories for a given company. + operationId: list-tracking-categories + parameters: + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TrackingCategories" + description: Success + summary: List tracking categories + tags: + - Tracking categories + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/data/trackingCategories/{trackingCategoryId}": + get: + deprecated: true + description: Gets the specified tracking categories for a given company. + operationId: get-tracking-category + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TrackingCategoryTree" + description: Success + summary: Get tracking categories + tags: + - Tracking categories + x-internal: true + parameters: + - $ref: "#/components/parameters/companyId" + - in: path + name: trackingCategoryId + required: true + schema: + type: string + "/companies/{companyId}/reports/agedCreditor": + get: + description: Returns aged creditors report for company that shows the total balance owed by a business to its suppliers over time. + operationId: get-aged-creditors-report + parameters: + - $ref: "#/components/parameters/reportDate" + - $ref: "#/components/parameters/numberOfPeriods" + - $ref: "#/components/parameters/periodLengthDays" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AgedCreditorReport" + description: OK + summary: Aged creditors report + tags: + - Reports + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/reports/agedCreditor/available": + get: + description: Indicates whether the aged creditor report is available for the company. + operationId: is-aged-creditors-report-available + responses: + "200": + content: + application/json: + schema: + type: boolean + description: OK + summary: Aged creditors report available + tags: + - Reports + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/reports/agedDebtor": + get: + description: Returns aged debtors report for company that shows the total outstanding balance due from customers to the business over time. + operationId: get-aged-debtors-report + parameters: + - $ref: "#/components/parameters/reportDate" + - $ref: "#/components/parameters/numberOfPeriods" + - $ref: "#/components/parameters/periodLengthDays" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AgedDebtorReport" + description: OK + summary: Aged debtors report + tags: + - Reports + parameters: + - $ref: "#/components/parameters/companyId" + "/companies/{companyId}/reports/agedDebtor/available": + get: + description: Indicates whether the aged debtor report is available for the company. + operationId: is-aged-debtor-report-available + responses: + "200": + content: + application/json: + schema: + type: boolean + description: OK + summary: Aged debtors report available + tags: + - Reports + parameters: + - $ref: "#/components/parameters/companyId" +components: + parameters: + accountId: + description: Unique identifier for an account + in: path + name: accountId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + allowSyncOnPushComplete: + in: query + name: allowSyncOnPushComplete + schema: + default: true + type: boolean + x-stoplight: + id: kc8ehjqr6p02q + attachmentId: + description: Unique identifier for an attachment + in: path + name: attachmentId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + bankAccountId: + description: Unique identifier for a bank account + in: path + name: bankAccountId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + billId: + description: Unique identifier for a bill + in: path + name: billId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + companyId: + in: path + name: companyId + required: true + schema: + description: Unique identifier for your SMB in Codat. + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + connectionId: + in: path + name: connectionId + required: true + schema: + description: Unique identifier for a company's data connection. + examples: + - 2e9d2c44-f675-40ba-8049-353bfcb5e171 + format: uuid + type: string + directCostId: + description: Unique identifier for a direct cost + in: path + name: directCostId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + directIncomeId: + description: Unique identifier for a direct income + in: path + name: directIncomeId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + forceUpdate: + in: query + name: forceUpdate + schema: + default: false + type: boolean + invoiceId: + description: Unique identifier for an invoice + in: path + name: invoiceId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + journalEntryId: + description: Unique identifier for a journal entry + in: path + name: journalEntryId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + numberOfPeriods: + description: Number of periods to include in the report. + in: query + name: numberOfPeriods + schema: + examples: + - 12 + format: int32 + type: integer + orderBy: + description: Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). + in: query + name: orderBy + required: false + schema: + examples: + - -modifiedDate + type: string + x-stoplight: + id: 4je9lwo02netu + page: + description: Page number. [Read more](https://docs.codat.io/using-the-api/paging). + in: query + name: page + required: true + schema: + default: 1 + examples: + - 1 + format: int32 + minimum: 0 + type: integer + x-stoplight: + id: 1318joqblpp4e + pageSize: + description: Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). + in: query + name: pageSize + schema: + default: 100 + examples: + - 100 + format: int32 + maximum: 5000 + minimum: 1 + type: integer + x-stoplight: + id: s2ika6rltk5y6 + periodLength: + in: query + name: periodLength + required: true + schema: + format: int32 + type: integer + periodLengthDays: + description: The length of period in days. + in: query + name: periodLengthDays + schema: + examples: + - 30 + format: int32 + type: integer + periodsToCompare: + in: query + name: periodsToCompare + required: true + schema: + format: int32 + type: integer + query: + description: Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). + in: query + name: query + required: false + schema: + type: string + x-stoplight: + id: gupdb9kt30hfq + reportDate: + description: Date the report is generated up to. + in: query + name: reportDate + schema: + examples: + - 2022-12-31 + format: date + type: string + startMonth: + in: query + name: startMonth + schema: + $ref: "#/components/schemas/DateTime" + supplierId: + description: Unique identifier for a supplier + in: path + name: supplierId + required: true + schema: + examples: + - 8a210b68-6988-11ed-a1eb-0242ac120002 + type: string + timeoutInMinutes: + in: query + name: timeoutInMinutes + schema: + format: int32 + type: integer + x-stoplight: + id: irz50qjbs3yef + schemas: + Account: + allOf: + - properties: + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + currentBalance: + description: Current balance in the account. + type: + - number + - "null" + description: + description: Description for the account. + type: + - string + - "null" + fullyQualifiedCategory: + description: |- + Full category of the account. For example: + Liability.Current or Income.Revenue. See example data. + type: + - string + - "null" + fullyQualifiedName: + description: |- + Full name of the account, for example: + - `Liability.Current.VAT` + - `Income.Revenue.Sales` + type: + - string + - "null" + id: + description: Identifier for the account, unique for the company. + type: string + isBankAccount: + description: Confirms whether the account is a bank account or not. + type: boolean + metadata: + $ref: "#/components/schemas/Metadata" + name: + description: Name of the account. + type: + - string + - "null" + nominalCode: + description: Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system. + type: + - string + - "null" + status: + $ref: "#/components/schemas/Account/definitions/accountStatus" + type: + $ref: "#/components/schemas/Account/definitions/accountType" + validDatatypeLinks: + description: "'The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see Valid Data Type Links.'" + items: + $ref: "#/components/schemas/ValidDataTypeLinks" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + accountRef: + description: Data types that reference an account, for example bill and invoice line items, use an accountRef that includes the ID and name of the linked account. + properties: + id: + description: "'id' from the Accounts data type." + type: string + name: + description: "'name' from the Accounts data type." + type: string + title: Account reference + type: object + accountStatus: + description: Status of the account + enum: + - Unknown + - Active + - Archived + - Pending + title: Account status + type: string + accountType: + description: Type of account + enum: + - Unknown + - Asset + - Expense + - Income + - Liability + - Equity + title: Account type + type: string + description: |- + > **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. + + View the coverage for accounts in the Data coverage explorer. + + ## Overview + + Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. + + The categories for an account include: + * Asset + * Expense + * Income + * Liability + * Equity. + + > **Accounts with no category** + > + > If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. + > + > This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. + required: + - type + - status + - isBankAccount + title: Account + type: object + AccountTransaction: + allOf: + - properties: + bankAccountRef: + $ref: "#/components/schemas/BankAccount/definitions/bankAccountRef" + description: Reference to the bank account the account transaction is recorded against. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + date: + $ref: "#/components/schemas/DateTime" + description: The date the account transaction was recorded in the platform. + id: + description: Identifier of the direct cost (unique to the company). + type: string + lines: + description: Array of account transaction lines. + items: + $ref: "#/components/schemas/AccountTransaction/definitions/accountTransactionLine" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Additional information about the account transaction, if available. + type: + - string + - "null" + status: + description: The status of the account transaction. + enum: + - Unknown + - Unreconciled + - Reconciled + - Void + type: string + totalAmount: + description: Total amount of the account transactions, inclusive of tax. + type: number + transactionId: + description: Identifier of the transaction (unique to the company). + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + accountTransactionLine: + properties: + amount: + description: Amount in the bill payment currency. + type: number + description: + description: Description of the account transaction. + nullable: true + type: string + recordRef: + $ref: "#/components/schemas/DirectCost/definitions/tracking/properties/invoiceTo" + description: Links an account transaction line to the underlying record that created it. + type: object + description: |- + > **Language tip:** In Codat, account transactions represent all transactions posted to a bank account within an accounting platform. For bank transactions posted within a banking platform, refer to [Banking transactions](https://docs.codat.io/banking-api#/operations/list-all-banking-transactions). + + > View the coverage for account transactions in the Data coverage explorer. + + ## Overview + + In Codat’s data model, account transactions represent bank activity within an accounting platform. All transactions that go through a bank account are recorded as account transactions. + + Account transactions are created as a result of different business activities, for example: + + * Payments: for example, receiving money for payment against an invoice. + * Bill payments: for example, spending money for a payment against a bill. + * Direct costs: for example, withdrawing money from a bank account, either for cash purposes or to make a payment. + * Direct incomes: for example, selling an item directly to a contact and receiving payment at point of sale. + * Transfers: for example, transferring money between two bank accounts. + + Account transactions is the parent data type of [payments](https://docs.codat.io/accounting-api#/schemas/Payment), [bill payments](https://docs.codat.io/accounting-api#/schemas/BillPayment), [direct costs](https://docs.codat.io/accounting-api#/schemas/DirectCost), [direct incomes](https://docs.codat.io/accounting-api#/schemas/DirectIncome), and [transfers](https://docs.codat.io/accounting-api#/schemas/Transfer). + title: Account transaction + type: object + AccountTransactions: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/AccountTransaction" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Accounts: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Account" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + AgedCreditorReport: + definitions: + agedCreditor: + properties: + agedCurrencyOutstanding: + description: Array of aged creditors by currency. + items: + properties: + agedOutstandingAmounts: + description: Array of outstanding amounts by period. + items: + properties: + amount: + description: The amount outstanding. + type: number + details: + description: Array of details. + items: + properties: + amount: + description: The amount outstanding. + type: number + name: + description: Name of data type with outstanding amount for given period. + type: string + title: Amounts outstanding by data type + type: object + type: array + fromDate: + $ref: "#/components/schemas/DateTime" + description: Start date of period. + toDate: + $ref: "#/components/schemas/DateTime" + description: End date of period. + title: Aged outstanding amount + type: object + type: array + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + title: Aged currency outstanding + type: object + type: array + supplierId: + description: Supplier ID of the aged creditor. + example: f594cefb-7750-4c3a-bab2-b5322026dee9 + type: string + supplierName: + description: Supplier name of the aged creditor. + example: John Doe + type: string + title: Aged creditor + type: object + description: |- + The Aged Creditors report shows the total balance owed by a business to its suppliers over time. + + You can generate it for a company based on recently synced data from your customers' accounting platforms. The report is available in the **Reports** tab in the Codat portal. + + Total assets or liabilities are grouped into 30-day periods for each supplier, up to the current date. You can adjust the report date, period length, and number of periods to show on each report. The data can be grouped by customer or currency. + + > It is not guaranteed that write-offs are included in the Aged Creditors report. + + ## Underlying data + + The Aged Creditors report is generated from a set of required data types: [Suppliers](https://docs.codat.io/accounting-api#/schemas/Supplier), [Bills](https://docs.codat.io/accounting-api#/schemas/Bill), [Bill credit notes](https://docs.codat.io/accounting-api#/schemas/BillCreditNote), and [Bill payments](https://docs.codat.io/accounting-api#/schemas/BillPayment). + + To generate the report, the underlying data types must have been synced within 24 hours of each other. Otherwise an error is displayed when you try to run the report. Sync the required data types by clicking the link in the error, and then run the report again. + + > The Aged Creditor report runs based on the **issue dates** of the underlying data types rather than the due date. + + ## Accessing the Aged Creditors report in Portal + + Apart from returning the report via the API as JSON and query, you can also return the Aged Creditors report in the Codat portal. + + 1. In the navigation bar, click **Companies**. + 2. Click the name of the company you want to generate the report for. The company's data page is displayed. + 3. Click the **Accounting** tab then click **Reports**. + 4. Select **Aged Creditors**. + 5. _(Optional)_ Edit the default reporting parameters. + a. You can change the report date in the **Date** box. By default, the report includes transactions that occurred up to, but not including, today's date. To include transactions for today, enter tomorrow's date. + b. In the **Period Length Days** box, select the default period length for each column (the default is 30 days). + b. In the **Number of Periods** box, enter the number of periods to show as columns in the report (the default is 4 periods). + 6. To run the report, click **Load aged creditors**. + 7. The report is generated and displayed at the bottom of the page. + + The report will be grouped per supplier and depending on the periods requested. The details indicates whether the amounts owed come from outstanding bills or bill credit notes. + examples: + - data: + - agedCurrencyOutstanding: + - agedOutstandingAmounts: + - amount: 1547.5 + details: + - amount: 1547.5 + name: Bills + fromDate: 2022-10-01T00:00:00Z + toDate: 2022-10-31T00:00:00Z + currency: GBP + customerId: f594cefb-7750-4c3a-bab2-b5322026dee9 + customerName: John Doe + generated: 2022-10-23T00:00:00Z + reportDate: 2022-10-23T00:00:00Z + properties: + data: + description: Array of aged creditor. + items: + $ref: "#/components/schemas/AgedCreditorReport/definitions/agedCreditor" + type: array + generated: + $ref: "#/components/schemas/DateTime" + description: Date and time the report was generated. + reportDate: + $ref: "#/components/schemas/DateTime" + description: Date the report is generated up to. + title: Aged creditors report + type: object + AgedDebtorReport: + definitions: + agedDebtor: + properties: + agedCurrencyOutstanding: + description: Array of aged debtors by currency. + items: + $ref: "#/components/schemas/AgedCreditorReport/definitions/agedCreditor/properties/agedCurrencyOutstanding/items" + type: array + customerId: + description: Customer ID of the aged debtor. + example: f594cefb-7750-4c3a-bab2-b5322026dee9 + type: string + customerName: + description: Customer name of the aged debtor. + example: John Doe + type: string + title: Aged debtor + type: object + description: |- + The Aged Debtors report shows the total outstanding balance due from customers to the business over time. + + You can generate it for a company based on recently synced data from your customers' accounting platforms. The report is available in the **Reports** tab in the Codat portal. + + Total assets or liabilities are grouped into 30-day periods for each customer, up to the current date. You can adjust the report date, period length, and number of periods to show on each report. The data can be grouped by customer or currency. + + > It is not guaranteed that write-offs are included in the Aged Debtors report. + + ## Underlying data + + The Aged Debtors report is generated from a set of required data types: [Customers](https://docs.codat.io/accounting-api#/schemas/Customer), [Invoices](https://docs.codat.io/accounting-api#/schemas/Invoice), [Credit notes](https://docs.codat.io/accounting-api#/schemas/CreditNote), and [Payments](https://docs.codat.io/accounting-api#/schemas/Payment). + + To generate the report, the underlying data types must have been synced within 24 hours of each other. Otherwise an error is displayed when you try to run the report. Sync the required data types by clicking the link in the error, and then run the report again. + + > The Aged Debtors report runs based on the **issue dates** of the underlying data types rather than the due date. + + ## Accessing the Aged Debtors report in Portal + + Apart from returning the report via the API as JSON and query, you can also return the Aged Debtors report in the Codat portal. + + 1. In the navigation bar, click **Companies**. + 2. Click the name of the company you want to generate the report for. The company's data page is displayed. + 3. Click the **Accounting** tab then click **Reports**. + 4. Select **Aged Debtors**. + 5. _(Optional)_ Edit the default reporting parameters. + a. You can change the report date in the **Date** box. By default, the report includes transactions that occurred up to, but not including, today's date. To include transactions for today, enter tomorrow's date. + b. In the **Period Length Days** box, select the default period length for each column (the default is 30 days). + b. In the **Number of Periods** box, enter the number of periods to show as columns in the report (the default is 4 periods). + 6. To run the report, click **Load aged debtors**. + 7. The report is generated and displayed at the bottom of the page. + + The report will be grouped per supplier and depending on the periods requested. The details indicates whether the amounts owed come from outstanding invoices or credit notes. + examples: + - data: + - agedCurrencyOutstanding: + - agedOutstandingAmounts: + - amount: 1547.5 + details: + - amount: 1547.5 + name: Invoices + fromDate: 2022-10-01T00:00:00Z + toDate: 2022-10-31T00:00:00Z + currency: GBP + customerId: f594cefb-7750-4c3a-bab2-b5322026dee9 + customerName: John Doe + generated: 2022-10-23T00:00:00Z + reportDate: 2022-10-23T00:00:00Z + properties: + data: + description: Array of aged debtors. + items: + $ref: "#/components/schemas/AgedDebtorReport/definitions/agedDebtor" + type: array + generated: + $ref: "#/components/schemas/DateTime" + description: Date and time the report was generated. + reportDate: + $ref: "#/components/schemas/DateTime" + description: Date the report is generated up to. + title: Aged debtors report + type: object + Attachment: + allOf: + - properties: + contentType: + description: |- + File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**. + + Supported file types vary per platform. + type: + - string + - "null" + dateCreated: + $ref: "#/components/schemas/DateTime" + fileSize: + description: File size in bytes. For example, if this reads **46153**, then the file size is 46kb. + format: int32 + type: + - integer + - "null" + id: + description: Identifier for the attachment, unique for the company in the accounting platform. + type: string + includeWhenSent: + description: If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting platform allows this. + type: boolean + name: + description: Name of the attachment file. + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + description: | + The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. + + > **Retrieving attachments** + > + > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. + + Unlike other data types, Codat doesn't support sync settings for attachments. + + View the coverage for accounts in the Data coverage explorer. + examples: [] + title: Attachment + type: object + AttachmentsDataset: + properties: + attachments: + items: + $ref: "#/components/schemas/Attachment" + type: + - array + - "null" + title: Attachments + type: object + x-internal: true + BalanceSheet: + additionalProperties: false + definitions: + balanceSheet: + properties: + assets: + $ref: "#/components/schemas/ReportLine" + description: ReportLines for assets. For example, fixed and current assets. + date: + $ref: "#/components/schemas/DateTime" + description: Point in time when a snapshot of a company's financial position is taken. + equity: + $ref: "#/components/schemas/ReportLine" + description: ReportLines for equities. For example, retained and current year earnings. See below. + liabilities: + $ref: "#/components/schemas/ReportLine" + description: ReportLines for liabilities. For example, current liabilities. + netAssets: + description: Value of net assets for a company in their base currency. + type: number + required: + - netAssets + type: object + description: |- + > View the coverage for balance sheet in the Data coverage explorer. + + ## Overview + + The balance sheet is a snapshot of a company's accounts at a single point in time that provides a statement of the assets, liabilities and equity of an organization. It gives interested parties an idea of the company's financial position, in addition to displaying what the company owns and owes. + + > **Balance sheet or profit and loss report?** + > + > A profit and loss report summarises the total revenue, expenses, and profit or loss during a specified time period. A balance sheet report shows the financial position of a company at a specific moment in time. + + **Structure of this report** + This report will reflect the structure and line descriptions that the business has set in their own accounting platform. + + **History** + By default, Codat pulls (up to) 24 months of balance sheets for a company. You can adjust this to fetch more history, where available, by updating the `monthsToSync` value for `balanceSheet` on the [data type settings endpoint](https://docs.codat.io/codat-api#/operations/post-profile-syncSettings). + + **Want to pull this in a standardised structure?** + Our [Enhanced Financials](https://docs.codat.io/assess/reports/enhanced-financials/financials) endpoints provide the same report under standardized headings, allowing you to pull it in the same format for all of your business customers. + properties: + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the balance sheet. + earliestAvailableMonth: + $ref: "#/components/schemas/DateTime" + description: Earliest available monthly report data. + nullable: true + mostRecentAvailableMonth: + $ref: "#/components/schemas/DateTime" + description: Most recent available monthly report data. + nullable: true + reports: + description: An array of balance sheet reports. + items: + $ref: "#/components/schemas/BalanceSheet/definitions/balanceSheet" + type: array + required: + - currency + - reports + title: Balance sheet + type: object + BankAccount: + allOf: + - properties: + accountName: + description: Name of the bank account in the accounting platform. + type: + - string + - "null" + accountNumber: + description: |- + Account number for the bank account. + + Xero integrations + Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. + + FreeAgent integrations + For Credit accounts, only the last four digits are required. For other types, the field is optional. + type: + - string + - "null" + accountType: + description: |- + The type of transactions and balances on the account. + For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. + For Debit accounts, positive balances are assets, and positive transactions **increase** assets. + enum: + - Unknown + - Credit + - Debit + title: Bank Account Type + type: string + x-internal: true + availableBalance: + description: Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. + type: + - number + - "null" + balance: + description: Balance of the bank account. + type: + - number + - "null" + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Base currency of the bank account. + iBan: + description: International bank account number of the account. Often used when making or receiving international payments. + type: + - string + - "null" + id: + description: Identifier for the account, unique for the company in the accounting platform. + type: string + institution: + description: The institution of the bank account. + type: + - string + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + nominalCode: + description: Code used to identify each nominal account for a business. + type: + - string + - "null" + overdraftLimit: + description: |- + Pre-arranged overdraft limit of the account. + + The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. + type: + - number + - "null" + sortCode: + description: |- + Sort code for the bank account. + + Xero integrations + The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + bankAccountRef: + description: Links to the Account transactions data type. + properties: + id: + description: Bank account 'id' for the account transaction. + type: string + name: + description: bank account 'name' for the account transaction. + type: string + title: Bank account reference + type: object + description: |- + > **Accessing Bank Accounts through Banking API** + > + > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. + > + > To view bank account data through the Banking API, please refer to the new datatype [here](https://docs.codat.io/banking-api#/schemas/Account) + + > View the coverage for bank accounts in the Data coverage explorer. + + ## Overview + + A list of bank accounts associated with a company and a specific data connection. + + Bank accounts data includes: + * The name and ID of the account in the accounting platform. + * The currency and balance of the account. + * The sort code and account number. + title: Bank account + type: object + BankAccountTransactions: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BankTransactions/definitions/bankTransactionLine" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + BankAccounts: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BankAccount" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + BankStatementAccount: + properties: + accountName: + type: + - string + - "null" + accountNumber: + type: + - string + - "null" + availableBalance: + type: + - number + - "null" + balance: + type: + - number + - "null" + currency: + type: + - string + - "null" + fromDate: + $ref: "#/components/schemas/DateTime" + iban: + type: + - string + - "null" + id: + type: string + institution: + type: + - string + - "null" + modifiedDate: + $ref: "#/components/schemas/ModifiedDates/allOf/0" + nominalCode: + type: + - string + - "null" + overdraftLimit: + type: + - number + - "null" + sortCode: + type: + - string + - "null" + sourceModifiedDate: + $ref: "#/components/schemas/ModifiedDates/allOf/1" + toDate: + $ref: "#/components/schemas/DateTime" + title: Bank statement account + type: object + BankTransactions: + definitions: + bankTransactionLine: + allOf: + - properties: + amount: + type: number + balance: + type: number + clearedOnDate: + $ref: "#/components/schemas/DateTime" + counterparty: + nullable: true + type: string + description: + nullable: true + type: string + id: + type: string + reconciled: + type: boolean + reference: + nullable: true + type: string + transactionType: + $ref: "#/components/schemas/BankTransactions/definitions/bankTransactionType" + type: object + - $ref: "#/components/schemas/ModifiedDates" + required: + - amount + - balance + - date + - reconciled + - transactionType + title: Bank transaction line + type: object + bankTransactionType: + description: Type of transaction for the bank statement line + enum: + - Unknown + - Credit + - Debit + - Int + - Div + - Fee + - SerChg + - Dep + - Atm + - Pos + - Xfer + - Check + - Payment + - Cash + - DirectDep + - DirectDebit + - RepeatPmt + - Other + title: Bank transaction type + type: string + description: |- + > **Accessing Bank Accounts through Banking API** + > + > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. + > + > To view bank account data through the Banking API, please refer to the new datatype [here](https://docs.codat.io/banking-api#/operations/list-all-banking-transactions) + + > View the coverage for bank transactions in the Data coverage explorer. + + ## Overview + + Transactional banking data for a specific company and account. + + Bank transactions include the: + * Amount of the transaction. + * Current account balance. + * Transaction type, for example, credit, debit, or transfer. + properties: + accountId: + type: + - string + - "null" + transactions: + items: + $ref: "#/components/schemas/BankTransactions/definitions/bankTransactionLine" + type: + - array + - "null" + title: Bank account transactions + type: object + BankTransactionsResponse: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BankTransactions" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Bill: + allOf: + - properties: + amountDue: + description: Amount outstanding on the bill. + type: + - number + - "null" + currency: + allOf: + - $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + - type: "null" + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + dueDate: + allOf: + - description: Date the supplier is due to be paid. + - $ref: "#/components/schemas/DateTime" + id: + description: Identifier for the bill, unique for the company in the accounting platform. + type: string + issueDate: + allOf: + - description: Date of the bill as recorded in the accounting platform. + - $ref: "#/components/schemas/DateTime" + lineItems: + description: Array of Bill line items. + items: + $ref: "#/components/schemas/Bill/definitions/billLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any private, company notes about the bill, such as payment information. + type: + - string + - "null" + paymentAllocations: + description: An array of payment allocations. + items: + definitions: + paymentAllocationPayment: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: The account that the allocated payment is made from or to. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency the payment has been made in. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + id: + description: Identifier of the allocated payment. + type: string + note: + description: Notes attached to the allocated payment. + nullable: true + type: string + paidOnDate: + $ref: "#/components/schemas/DateTime" + description: The date the payment was paid. + reference: + description: Reference to the allocated payment. + nullable: true + type: string + totalAmount: + description: Total amount that was paid. + type: number + type: object + properties: + allocation: + properties: + allocatedOnDate: + $ref: "#/components/schemas/DateTime" + description: The date the payment was allocated. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: The currency of the transaction. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + totalAmount: + description: The total amount that has been allocated. + type: number + type: object + payment: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items/definitions/paymentAllocationPayment" + required: + - payment + - allocation + title: Payment allocation + type: object + type: + - array + - "null" + purchaseOrderRefs: + items: + $ref: "#/components/schemas/PurchaseOrder/definitions/purchaseOrderRef" + type: + - array + - "null" + reference: + description: User-friendly reference for the bill. + type: + - string + - "null" + status: + $ref: "#/components/schemas/Bill/definitions/billStatus" + subTotal: + description: Total amount of the bill, excluding any taxes. + type: number + supplementalData: + description: Reference to a configured dynamic key value pair that is unique to the accounting platform. This feature is in private beta, contact us if you would like to learn more. + properties: + content: + additionalProperties: + additionalProperties: {} + type: object + type: + - object + - "null" + type: object + supplierRef: + $ref: "#/components/schemas/Supplier/definitions/supplierRef" + taxAmount: + description: Amount of tax on the bill. + type: number + totalAmount: + description: Amount of the bill, including tax. + type: number + withholdingTax: + items: + properties: + amount: + type: number + name: + minLength: 1 + type: string + required: + - amount + - name + type: object + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + billLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Friendly name of the goods or services received. + nullable: true + type: string + discountAmount: + description: |- + Numerical value of any discounts applied. + + Do not use to apply discounts in Oracle NetSuite—see Oracle NetSuite integration reference. + nullable: true + type: number + discountPercentage: + nullable: true + type: number + isDirectCost: + type: boolean + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the product, service type, or inventory item to which the line item is linked. + quantity: + description: Number of units of goods or services received. + type: number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax. + nullable: true + type: number + taxAmount: + description: Amount of tax for the line. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: Total amount of the line, including tax. + nullable: true + type: number + tracking: + $ref: "#/components/schemas/BillCreditNote/definitions/billCreditNoteLineItem/properties/tracking" + trackingCategoryRefs: + deprecated: true + description: Collection of categories against which this item is tracked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: Price of each unit of goods or services. + type: number + required: + - unitAmount + - quantity + type: object + billStatus: + description: Current state of the bill. + enum: + - Unknown + - Open + - PartiallyPaid + - Paid + - Void + - Draft + type: string + description: |- + > **Invoices or bills?** + > + > In Codat, bills are for accounts payable only. For the accounts receivable equivalent of bills, see [Invoices](https://docs.codat.io/accounting-api#/schemas/Invoice). + + View the coverage for bills in the Data coverage explorer. + + ## Overview + + In Codat, a bill contains details of: + * When the bill was recorded in the accounting system. + * How much the bill is for and the currency of the amount. + * Who the bill was received from — the *supplier*. + * What the bill is for — the *line items*. + + Some accounting platforms give a separate name to purchases where the payment is made immediately, such as something bought with a credit card or online payment. One example of this would be QuickBooks Online's *expenses*. + + You can find these types of transactions in our [Direct costs](https://docs.codat.io/accounting-api#/schemas/DirectCost) data model. + required: + - issueDate + - status + - subTotal + - taxAmount + - totalAmount + title: Bill + type: object + BillCreditNote: + allOf: + - properties: + allocatedOnDate: + $ref: "#/components/schemas/DateTime" + description: Date the bill credit note was fully refunded or allocated. + nullable: true + billCreditNoteNumber: + description: Friendly reference for the bill credit note. + type: + - string + - "null" + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the bill credit note. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + discountPercentage: + description: Percentage rate of any discount applied to the bill credit note. + type: number + id: + description: Identifier for the bill credit note that is unique to a company in the accounting platform. + type: string + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date the bill credit note was issued by the supplier. + lineItems: + description: "An array of line " + items: + $ref: "#/components/schemas/BillCreditNote/definitions/billCreditNoteLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information about the bill credit note. + type: + - string + - "null" + paymentAllocations: + description: An array of payment allocations. + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items" + type: + - array + - "null" + remainingCredit: + description: Amount of the bill credit note that is still outstanding. + type: number + status: + $ref: "#/components/schemas/BillCreditNote/definitions/billCreditNoteStatus" + subTotal: + description: Total amount of the bill credit note, including discounts but excluding tax. + type: number + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + supplierRef: + $ref: "#/components/schemas/Supplier/definitions/supplierRef" + totalAmount: + description: Total amount of credit that has been applied to the business' account with the supplier, including discounts and tax. + type: number + totalDiscount: + description: Total value of any discounts applied. + type: number + totalTaxAmount: + description: Amount of tax included in the bill credit note. + type: number + withholdingTax: + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/withholdingTax/items" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + billCreditNoteLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: + description: Friendly name of each line item. For example, the goods or service for which credit has been received. + nullable: true + type: string + discountAmount: + description: Value of any discounts applied. + nullable: true + type: number + discountPercentage: + description: Percentage rate of any discount applied to the line item. + nullable: true + type: number + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the item the line is linked to. + quantity: + description: Number of units of the goods or service for which credit has been received. + type: number + subTotal: + description: Amount of credit associated with the line item, including discounts but excluding tax. + nullable: true + type: number + taxAmount: + description: Amount of tax associated with the line item. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + totalAmount: + description: Total amount of the line item, including discounts and tax. + nullable: true + type: number + tracking: + definitions: + billedToType: + enum: + - Unknown + - NotApplicable + - Customer + - Project + type: string + description: Categories, and a project and customer, against which the item is tracked. + properties: + categoryRefs: + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + type: array + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + isBilledTo: + $ref: "#/components/schemas/BillCreditNote/definitions/billCreditNoteLineItem/properties/tracking/definitions/billedToType" + isRebilledTo: + $ref: "#/components/schemas/BillCreditNote/definitions/billCreditNoteLineItem/properties/tracking/definitions/billedToType" + projectRef: + $ref: "#/components/schemas/ProjectRef" + required: + - categoryRefs + - isBilledTo + - isRebilledTo + title: Tracking + type: object + x-stoplight: + id: 2158cacd7b329 + trackingCategoryRefs: + deprecated: true + description: Reference to the tracking categories to which the line item is linked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: Unit price of the goods or service. + type: number + required: + - unitAmount + - quantity + type: object + billCreditNoteStatus: + description: Current state of the bill credit note + enum: + - Unknown + - Draft + - Submitted + - Paid + - Void + - PartiallyPaid + type: string + description: |- + > **Bill credit notes or credit notes?** + > + > In Codat, bill credit notes represent accounts payable only. For accounts receivable, see [Credit notes](https://docs.codat.io/accounting-api#/schemas/CreditNote). + + View the coverage for bill credit notes in the Data coverage explorer. + + ## Overview + + A bill credit note is issued by a supplier for the purpose of recording credit. For example, if a supplier was unable to fulfil an order that was placed by a business, or delivered damaged goods, they would issue a bill credit note. A bill credit note reduces the amount a business owes to the supplier. It can be refunded to the business or used to pay off future bills. + + In the Codat API, a bill credit note is an accounts payable record issued by a [supplier](https://docs.codat.io/accounting-api#/schemas/Supplier). + + A bill credit note includes details of: + * The original and remaining credit. + * Any allocations of the credit against other records, such as [bills](https://docs.codat.io/accounting-api#/schemas/Bill). + * The supplier that issued the bill credit note. + examples: + - billCreditNoteNumber: "14763237" + currency: USD + id: 6a0e9dfb-87b0-47d3-aaaf-9753ae9e757d + issueDate: 2019-02-18T16:03:07.268Z + lineItems: + - accountRef: + id: 3f267b10-757d-44c0-bef9-20f70cc8fbe3 + description: AcmeMagnet + discountAmount: 0 + itemRef: + id: "3" + quantity: 4 + subTotal: 100 + taxAmount: 10 + taxRateRef: + id: 6c88aff3-7cb9-4980-a3d3-443e72e02498 + totalAmount: 110 + trackingCategoryRefs: + - id: department_1 + name: ACMERockets + - id: costcode_2 + name: ACM2-ACMESigns + unitAmount: 25 + - accountRef: + id: 3f267b10-757d-44c0-bef9-20f70cc8fbe3 + description: ACMEDisintegratingPistol + discountAmount: 0 + itemRef: + id: 3abf0883-03f7-44c6-bc15-1372522d25e1 + quantity: 3 + subTotal: 75 + taxAmount: 7.5 + taxRateRef: + id: 6c88aff3-7cb9-4980-a3d3-443e72e02498 + totalAmount: 82.5 + unitAmount: 25 + - accountRef: + id: 3f267b10-757d-44c0-bef9-20f70cc8fbe3 + description: ACMEWhippedCreamDispenser + discountAmount: 0 + itemRef: + id: 3691f3d9-0ff7-4358-8a93-bed31c1b4b03 + quantity: 6 + subTotal: 312 + taxAmount: 31.2 + taxRateRef: + id: 6c88aff3-7cb9-4980-a3d3-443e72e02498 + totalAmount: 343.2 + unitAmount: 52 + - accountRef: + id: 3f267b10-757d-44c0-bef9-20f70cc8fbe3 + description: ACMEJetPropelledPogoStick + discountAmount: 0 + itemRef: + id: 075410d4-7edc-4936-ba52-9e1e43cbe300 + quantity: 1 + subTotal: 130 + taxAmount: 27.3 + taxRateRef: + id: d606732b-db18-44d7-823b-7f15f42c32ea + totalAmount: 157.3 + unitAmount: 130 + note: Track separately + remainingCredit: 693 + status: Submitted + supplierRef: + id: 67C6A7A1-5E84-4AC4-B950-24A114E379D0 + supplierName: Chin's Gas and Oil + totalAmount: 693 + required: + - totalAmount + - totalDiscount + - subTotal + - totalTaxAmount + - discountPercentage + - remainingCredit + - status + title: Bill credit note + type: object + BillCreditNotes: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BillCreditNote" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + BillPayment: + allOf: + - properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Account the payment is linked to in the accounting platform. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + date: + $ref: "#/components/schemas/DateTime" + description: Date the bill payment was recorded in the accounting software. + id: + description: Identifier for the bill payment, unique for the company in the accounting platform. + type: string + lines: + description: An array of bill payment lines. + items: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLine" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Additional information associated with the payment. + type: + - string + - "null" + paymentMethodRef: + $ref: "#/components/schemas/PaymentMethod/definitions/paymentMethodRef" + description: The Payment Method to which the payment is linked in the accounting platform. + reference: + description: Additional information associated with the payment. + type: + - string + - "null" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + supplierRef: + $ref: "#/components/schemas/Supplier/definitions/supplierRef" + totalAmount: + description: Amount of the payment in the payment currency. This value never changes and represents the amount of money that is paid into the supplier's account. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + billPaymentLine: + properties: + allocatedOnDate: + $ref: "#/components/schemas/DateTime" + description: AllocatedOnDate must be specified and be later than the issue date of the bill. + amount: + description: Amount in the bill payment currency. + type: number + links: + items: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink" + nullable: true + type: array + required: + - amount + type: object + billPaymentLineLink: + properties: + amount: + description: |- + Amount by which the balance of the linked entity is altered, in the currency of the linked entity. + + - A negative link amount reduces the outstanding amount on the accounts payable account. + - A positive link amount increases the outstanding amount on the accounts payable account. + nullable: true + type: number + currencyRate: + description: |- + Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. + + Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. + + Where the currency rate is provided by the underlying accounting platform, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). + + For accounting platforms which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. + + ## Examples with base currency of GBP + + | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | + | :--------------- | :------------- | :------------ | :------------------------- | + | **USD** | $20 | 0.781 | £15.62 | + | **EUR** | €20 | 0.885 | £17.70 | + | **RUB** | ₽20 | 0.011 | £0.22 | + + ## Examples with base currency of USD + + | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | + | :--------------- | :------------- | :------------ | :------------------------- | + | **GBP** | £20 | 1.277 | $25.54 | + | **EUR** | €20 | 1.134 | $22.68 | + | **RUB** | ₽20 | 0.015 | $0.30 | + nullable: true + title: Currency rate + type: number + id: + description: Unique identifier of the transaction represented by the link. + nullable: true + type: string + type: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLinkType" + required: + - type + type: object + billPaymentLineLinkType: + description: Types of links to bill payment lines. + enum: + - Unknown + - Unlinked + - Bill + - Other + - CreditNote + - BillPayment + - PaymentOnAccount + - Refund + - ManualJournal + - Discount + type: string + description: | + > **Bill payments or payments?** + > + > In Codat, bill payments represent accounts payable only. For accounts receivable, see [payments](https://docs.codat.io/accounting-api#/schemas/Payment), which includes [invoices](https://docs.codat.io/accounting-api#/schemas/Invoice) and [credit notes](https://docs.codat.io/accounting-api#/schemas/CreditNote). + + > View the coverage for bill payments in the Data coverage explorer. + + ## Overview + + Bill payments include all accounts payable transaction data. This includes [bills](https://docs.codat.io/accounting-api#/schemas/Bill) and [credit notes against bills](https://docs.codat.io/accounting-api#/schemas/BillCreditNote). + + A bill payment in Codat usually represents an allocation of money within any customer accounts payable account. This includes, but is not strictly limited to: + + - A payment made against a bill — for example, a credit card payment, cheque payment, or cash payment. + - An allocation of a supplier's credit note to a bill or perhaps a refund. + - A bill payment made directly to an accounts payable account. This could be an overpayment or a prepayment, or a refund of a payment made directly to an accounts payable account. + + Depending on the bill payments which are allowed by the underlying accounting package, some of these types may be combined. Please see the example data section for samples of what these cases look like. + + In Codat, a bill payment contains details of: + + - When the bill payment was recorded in the accounting system. + - How much it is for and in the currency. + - Who the payment has been paid to, the _supplier_. + - The types of bill payments, the _line items_. + + Some accounting platforms give a separate name to purchases where the payment is made immediately, such as something bought with a credit card or online payment. One example of this would be QuickBooks Online's _expenses_. You can find these types of transactions in our [Direct costs](https://docs.codat.io/accounting-api#/schemas/DirectCost) data model. + + Bill payments is a child data type of [account transactions](https://docs.codat.io/accounting-api#/schemas/AccountTransaction). + + --- + + ## Bill payment types + + ### Payment of a bill + + A payment paying a single bill should have the following properties: + + - A `totalAmount` indicating the amount of the bill that was paid. This is always positive. + - A `lines` array containing one element with the following properties: + - An `amount` equal to the `totalAmount` above. + - A `links` array containing one element with the following properties: + - A `type` indicating the type of link, in this case a `Bill`. + - An `id` containing the ID of the bill that was paid. + - An amount of `-totalAmount` (negative `totalAmount`), indicating that the entirety of the paid amount is allocated to the bill. + + ### Payment of multiple bills + + It is possible for one payment to pay multiple bills. This can be represented using two possible formats, depending on how the supplier keeps their books: + + 1. The payment has multiple entries in its **lines** array, one for each bill that is paid. Each line will follow the above example for paying a bill, and the rules detailed in the data model. + 2. The payment has a line with multiple links to each bill. This occurs when the proportion of the original payment allocated to each bill is not available. + + Each line is the same as those described above, with the **amount** indicating how much of the payment is allocated to the bill. The **amount** on the lines sum to the **totalAmount** on the payment. + + > Pushing batch payments to Xero + > + > When pushing a single bill payment to Xero to pay multiple bills, only the first format is supported—multiple entries in the payment **lines** array. + + ### Payments and refunds on account + + A payment on account, that is a payment that doesn’t pay a specific bill, has one entry in its lines array. + + The line has the following properties: + + - A **totalAmount** indicating the amount paid by a supplier or refunded to them by a company. A payment to the supplier is always negative. A refund is always positive. + - A **links** array containing one element with the following properties: + - A **type** indicating the type of link. For a payment this is `PaymentOnAccount`. For a refund this is `Refund`. + - The **id** containing the ID of the supplier. + - An amount for the link is `0` **totalAmount** or the amount of the payment or refund. + + It is possible to have a payment that is part on account and part allocated to a bill. Each line should follow the examples above. + + ### Using a credit note to pay a bill + + The payment of a bill using a credit note has one entry in its `lines` array. This **line** has the following properties: + + - An **amount** indicating the amount of money moved, which in this case is `0`, as the credit note and bill allocation must balance each other. + - A **links** array containing two elements: + - The first link has: + - A **type** indicating the type of link, in this case a `Bill`. + - An **id** containing the ID of the bill that was paid. + - The second link has: + - A **type** indicating the type of link, in this case a `CreditNote`. + - An **id** containing the ID of the credit note used by this payment. + + The **amount** field on the **line** equals the **totalAmount** on the payment. + + ### Refunding a credit note + + A bill payment refunding a credit note has one entry in its **lines** array. This line has the following properties: + + - An **amount** indicating the amount of the credit note that was refunded. This is always negative, indicating that it is a refund. + - A **links** array containing one element with the following properties: + - A **type** indicating the type of `link`, in this case a `CreditNote`. + - An **id** containing the ID of the credit note that was refunded. + + The **totalAmount** field on the payment equals the line's **amount** field. These are both negative, as this is money leaving accounts payable. + + ### Refunding a payment + + If a payment is refunded, for example, when a company overpaid a bill and the overpayment is returned, there are two payment records: + + - One for the incoming overpayment. + - Another for the outgoing refund. + + The payment issuing the refund is identified by the fact that the **totalAmount** is negative. This payment has one entry in its lines array that have the following properties: + + - An **amount** indicating the amount that was refunded. This is always negative. + - A **links** array containing one element with the following properties: + - A **type** indicating the type of a the link, in this case a `BillPayment`. + - An **id** containing the ID of the payment that was refunded. + + The **amount** field on the line equals the **totalAmount** on the payment and is negative as this is money leaving accounts payable. + + The payment that was refunded can be identified as it has a line where the `amount` on its `line` is positive and the type of the link is `Refund`. This payment may have several entries in its **lines** array if it was partly used to pay an bill. For example, a £1,050 payment paying a £1,000 bill with a refund of £50 has two lines: + + - One for £1,000 linked to the bill that was paid + - Another for £50 linked to the payment that refunded the over payment. This link is of type `Refund` but the ID corresponds to a bill payment. + + The line linked to the bill payment has the following properties: + + - An **amount** indicating the amount that was refunded. This is positive as its money that was added to accounts payable, but is balanced out by the negative amount of the refund. + - A **links** array containing one element with the following properties: + - A **type** indicating the type of the link, in this case a `Refund`. + - An **id** containing the ID of the payment that refunded this line. + + > Linked payments + > + > Not all accounting packages support linked payments in this way. In these platforms you may see a payment on account and a refund on account. + + ## Foreign currencies + + There are two types of currency rate that are detailed in the bill payments data type: + + Payment currency rate: + + - Base currency of the accounts payable account. + - Foreign currency of the bill payment. + + Payment line link currency rate: + + - Base currency of the item that the link represents. + - Foreign currency of the payment. + + These two rates allow the calculation of currency loss or gain for any of the transactions affected by the payment lines. The second rate is used when a bill payment is applied to an item in a currency that does not match either: + + - The base currency for the accounts payable account. + - The currency of the item. + examples: + - lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + totalAmount: 1000 + - lines: + - amount: 0 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + id: y + type: CreditNote + totalAmount: 0 + - lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + links: + - amount: -1000 + id: y + type: PaymentOnAccount + totalAmount: 2000 + - lines: + - amount: -1000 + links: + - amount: 1000 + id: y + type: CreditNote + totalAmount: -1000 + - lines: + - amount: -1000 + links: + - amount: 1000 + id: y + type: PaymentOnAccount + totalAmount: -1000 + - lines: + - amount: 0 + links: + - amount: -750 + id: x + type: Bill + - amount: 750 + id: y + type: CreditNote + - amount: 250 + links: + - amount: -250 + id: x + type: Bill + totalAmount: 250 + - lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + modifiedDate: 2022-10-23T00:00:00Z + sourceModifiedDate: 2022-10-23T00:00:00Z + totalAmount: 1000 + - lines: + - amount: 0 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + id: y + type: CreditNote + - amount: 0 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + id: z + type: CreditNote + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + links: + - amount: -1000 + id: customer-001 + type: PaymentOnAccount + totalAmount: 2000 + - lines: + - amount: 0 + links: + - amount: -1000 + id: w + type: Bill + - amount: -1000 + id: x + type: Bill + - amount: 1000 + id: y + type: CreditNote + - amount: 1000 + id: z + type: CreditNote + totalAmount: 0 + - lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + modifiedDate: 2022-10-23T00:00:00Z + sourceModifiedDate: 2022-10-23T00:00:00Z + totalAmount: 1000 + - date: 1901-01-01 + id: "001" + lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + - amount: 4000 + links: + - amount: -4000 + id: y + type: PaymentOnAccount + totalAmount: 5000 + - date: 1901-01-01 + id: "001" + lines: + - amount: 1000 + links: + - amount: -1000 + id: x + type: Bill + - amount: 1000 + links: + - amount: -1000 + id: y + type: Bill + - amount: 3000 + links: + - amount: -3000 + id: y + type: PaymentOnAccount + totalAmount: 5000 + - lines: + - amount: 500 + links: + - amount: -1000 + id: a + type: Bill + - amount: -1000 + id: b + type: Bill + - amount: 750 + id: y + type: CreditNote + - amount: 750 + id: z + type: CreditNote + totalAmount: 500 + required: + - date + title: Bill payment + type: object + BillPayments: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BillPayment" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Bills: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Bill" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + CashFlowStatement: + definitions: + cashFlowStatement: + properties: + cashPayments: + $ref: "#/components/schemas/ReportLine" + description: ReportLines for cash payments to suppliers for the purchase of goods or services. + cashReceipts: + $ref: "#/components/schemas/ReportLine" + description: ReportLines for cash receipts from the sale of goods. + fromDate: + $ref: "#/components/schemas/DateTime" + description: Start date for the reporting period. + toDate: + $ref: "#/components/schemas/DateTime" + description: End date for the reporting period. + title: Cash flow statement + type: object + reportBasis: + description: Accounting method used when aggregating the report data. In this case, `Cash`. + enum: + - Unknown + - Accrual + - Cash + title: Report basis + type: string + reportInput: + description: Accounting method used to prepare the cash flow statement. + enum: + - Unknown + - Indirect + - Direct + type: string + description: |- + > View the coverage for cash flow statement in the Data coverage explorer. + + > **Operating activities only** + > + > Currently, the cash flow statement shows cash that flows into and out of the company from operating activities *only*. Operating activities generate cash from the sale of goods or services. + + ## Overview + + A cash flow statement is a financial report that records all cash that is received or spent by a company during a given period. It gives you a clearer picture of the company’s performance, and their ability to pay creditors and finance growth. + + > **Cash flow statement or balance sheet?** + > + > Look at the cash flow statement to understand a company's ability to pay its bills. Although the balance sheet may show healthy earnings at a specific point in time, the cash flow statement allows you to see whether the company is meeting its financial commitments, such as paying creditors or its employees. + properties: + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of all values in the cash flow statement. + earliestAvailableMonth: + $ref: "#/components/schemas/DateTime" + nullable: true + mostRecentAvailableMonth: + $ref: "#/components/schemas/DateTime" + nullable: true + reportBasis: + $ref: "#/components/schemas/CashFlowStatement/definitions/reportBasis" + reportInput: + $ref: "#/components/schemas/CashFlowStatement/definitions/reportInput" + reports: + description: Array of cash flow statements. + items: + $ref: "#/components/schemas/CashFlowStatement/definitions/cashFlowStatement" + type: array + required: + - reports + - reportBasis + - reportInput + - currency + title: Cash flow statement + type: object + CompanyDataset: + description: |- + > View the coverage for company info in the Data coverage explorer. + + Company info provides standard details about a linked company such as their address, phone number, and company registration. + + > **Company information or companies?** + > + > Company information is standard information that is held in the accounting platform about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. + examples: + - accountingPlatformRef: 4444e827-401b-4925-92cb-d79086bf3b6b + addresses: + - city: London + country: United Kingdom + line1: Warner House + line2: 98 Theobald's Road + postalcode: WC1X 8WB + region: "" + type: Billing + - city: San Pablo + country: "" + line1: 123 Sierra Way + line2: "" + postalCode: "87999" + region: CA + type: Unknown + baseCurrency: USD + companyLegalName: ACME Corporation Ltd. + companyName: ACME Corporation + createdDate: 2020-02-03T16:42:02Z + financialYearStartDate: 2019-04-01T00:00:00Z + ledgerLockDate: 2019-03-04T12:08:01.881Z + phoneNumbers: + - number: 010 1234 5678 + type: Landline + registrationNumber: "1234567890" + sourceUrls: + url1: https://go.xero.com/organisationlogin/default.aspx?shortcode=!rxs0Q + url2: https://reporting.xero.com/!rxs0Q + taxNumber: GB 123456789 + webLinks: + - type: Website + url: https://www.wbsl.com/ + properties: + accountingPlatformRef: + description: Identifier or reference for the company in the accounting platform. + type: + - string + - "null" + addresses: + description: An array of Addresses. + items: + definitions: + addressType: + description: The type of the address + enum: + - Unknown + - Billing + - Delivery + type: string + properties: + city: + description: City of the customer address. + type: + - string + - "null" + country: + description: Country of the customer address. + type: + - string + - "null" + line1: + description: Line 1 of the customer address. + type: + - string + - "null" + line2: + description: Line 2 of the customer address. + type: + - string + - "null" + postalCode: + description: Postal code or zip code. + type: + - string + - "null" + region: + description: Region of the customer address. + type: + - string + - "null" + type: + $ref: "#/components/schemas/CompanyDataset/properties/addresses/items/definitions/addressType" + required: + - type + type: object + type: + - array + - "null" + baseCurrency: + description: Currency set in the accounting platform of the linked company. Used by the currency rate. + type: + - string + - "null" + companyLegalName: + description: Registered legal name of the linked company. + type: + - string + - "null" + companyName: + description: Name of the linked company. + type: + - string + - "null" + createdDate: + $ref: "#/components/schemas/DateTime" + description: Date the linked company was created in the accounting platform. + financialYearStartDate: + $ref: "#/components/schemas/DateTime" + description: Start date of the financial year for the company. + ledgerLockDate: + $ref: "#/components/schemas/DateTime" + description: If set in the accounting platform, the date (in the ISO 8601 date/time format) after which accounting transactions cannot be edited. Commonly used when books are closed at year-end. + phoneNumbers: + description: An array of phone numbers. + items: + definitions: + phoneNumberType: + description: The type of phone number + enum: + - Primary + - Landline + - Mobile + - Fax + - Unknown + type: string + properties: + number: + description: A phone number. + examples: + - +44 25691 154789 + - (877) 492-8687 + - 01224 658 999 + type: + - string + - "null" + type: + $ref: "#/components/schemas/CompanyDataset/properties/phoneNumbers/items/definitions/phoneNumberType" + required: + - number + - type + title: Phone + type: object + x-internal: true + type: + - array + - "null" + registrationNumber: + description: Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House. + type: + - string + - "null" + sourceUrls: + additionalProperties: + type: + - string + - "null" + description: |- + URL addresses for the accounting source. + + For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero). + type: + - object + - "null" + taxNumber: + description: Company tax number. + type: + - string + - "null" + webLinks: + description: An array of weblinks. + items: + description: Weblink associated with the company. + examples: + - type: Website + url: https://codat.io + properties: + type: + description: The type of the weblink. + enum: + - Website + - Social + - Unknown + type: string + url: + description: The full URL for the weblink. + format: url + type: string + title: Weblink + type: object + type: + - array + - "null" + title: Company information + type: object + CreateAccountResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Account" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateBankAccountResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Account" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateBankTransactionsResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BankTransactions" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateBillCreditNoteResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BillCreditNote" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateBillPaymentResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BillPayment" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateBillResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Bill" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateCreditNoteResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/CreditNote" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateCustomerResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Customer" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateDirectCostResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/DirectCost" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateDirectIncomeResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/DirectIncome" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateInvoiceResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Invoice" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateItemResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Item" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateJournalEntryResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/JournalEntry" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreatePaymentResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Payment" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreatePurchaseOrderResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/PurchaseOrder" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateSupplierResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Supplier" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreateTransferResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Transfer" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + CreditNote: + allOf: + - properties: + additionalTaxAmount: + type: number + additionalTaxPercentage: + type: number + allocatedOnDate: + $ref: "#/components/schemas/DateTime" + description: Date on which the credit note was fully allocated. + creditNoteNumber: + description: Friendly reference for the credit note. + type: + - string + - "null" + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the credit note. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + description: Reference to the customer the credit note has been issued to. + discountPercentage: + description: Percentage rate (from 0 to 100) of discounts applied to the credit note. + type: number + id: + description: Identifier for the credit note, unique to the company in the accounting platform. + type: string + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date of the credit note as recorded in the accounting system. + lineItems: + items: + $ref: "#/components/schemas/CreditNote/definitions/creditNoteLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information about the credit note. Where possible, Codat links to a data field in the accounting platform that is publicly available. This means that the contents of the note field are included when a credit note is emailed from the accounting platform to the customer. + type: + - string + - "null" + paymentAllocations: + description: An array of payment allocations. + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items" + type: + - array + - "null" + remainingCredit: + description: Unused balance of totalAmount originally raised. + type: number + status: + $ref: "#/components/schemas/CreditNote/definitions/creditNoteStatus" + description: Current state of the credit note. + subTotal: + description: Value of the credit note, including discounts and excluding tax. + type: number + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + totalAmount: + description: Total amount of credit that has been applied to the customer's accounts receivable + type: number + totalDiscount: + description: Any discounts applied to the credit note amount. + type: number + totalTaxAmount: + description: Any tax applied to the credit note amount. + type: number + withholdingTax: + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/withholdingTax/items" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + creditNoteLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Friendly name of each line item. For example, the goods or service for which credit has been issued. + nullable: true + type: string + discountAmount: + description: Value of any discounts applied. + nullable: true + type: number + discountPercentage: + description: Percentage rate of any discount applied to the line item. + nullable: true + type: number + isDirectIncome: + type: boolean + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the item the line is linked to. + quantity: + description: Number of units of the goods or service for which credit has been issued. + type: number + subTotal: + description: Amount of credit associated with the line item, including discounts but excluding tax. + nullable: true + type: number + taxAmount: + description: Amount of tax associated with the line item. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: Total amount of the line item, including discounts and tax. + nullable: true + type: number + tracking: + definitions: + billedToType: + enum: + - Unknown + - NotApplicable + - Project + type: string + description: Categories, and a project and customer, against which the item is tracked. + properties: + categoryRefs: + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + type: array + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + isBilledTo: + $ref: "#/components/schemas/CreditNote/definitions/creditNoteLineItem/properties/tracking/definitions/billedToType" + isRebilledTo: + $ref: "#/components/schemas/CreditNote/definitions/creditNoteLineItem/properties/tracking/definitions/billedToType" + projectRef: + $ref: "#/components/schemas/ProjectRef" + required: + - categoryRefs + - isBilledTo + - isRebilledTo + title: Tracking + type: object + trackingCategoryRefs: + deprecated: true + description: Reference to the tracking categories to which the line item is linked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: Unit price of the goods or service. + type: number + required: + - unitAmount + - quantity + type: object + creditNoteStatus: + enum: + - Unknown + - Draft + - Submitted + - Paid + - Void + - PartiallyPaid + type: string + description: |- + > View the coverage for credit notes in the Data coverage explorer. + + ## Overview + + Think of a credit note as a voucher issued to a customer. It is a reduction that can be applied against one or multiple invoices. A credit note can either reduce the amount owed or cancel out an invoice entirely. + + In the Codat system a credit note is issued to a [customer's](https://docs.codat.io/accounting-api#/schemas/Customer) accounts receivable. + + It contains details of: + * The amount of credit remaining and its status. + * Payment allocations against the payments type, in this case an invoice. + * Which customers the credit notes have been issued to. + examples: + - - allocatedOnDate: null + creditNoteNumber: "5239277" + currency: USD + currencyRate: null + customerRef: + companyName: Tool Hire Company + id: b5511228-b9ef-4713-91b1-ad2cf60eadb1 + discountPercentage: 0 + id: 0316bd24-8a01-4a3a-a0e5-a73f14ebcbec + issueDate: 2018-03-28T21:28:58.249Z + lineItems: + - accountRef: + id: 3f267b10-757d-44c0-bef9-20f70cc8fbe3 + name: null + description: Anvil10000Lb + discountAmount: 0 + discountPercentage: null + itemRef: + id: "1" + name: null + quantity: 10 + subTotal: 500 + taxAmount: 50 + taxRateRef: + id: 6c88aff3-7cb9-4980-a3d3-443e72e02498 + name: null + totalAmount: 550 + unitAmount: 50 + modifiedDate: null + note: More information available on request. + paymentAllocations: [] + remainingCredit: 550 + sourceModifiedDate: null + status: Submitted + subTotal: 0 + totalAmount: 550 + totalDiscount: 0 + totalTaxAmount: 0 + required: + - totalAmount + - totalDiscount + - subTotal + - totalTaxAmount + - discountPercentage + - remainingCredit + - status + title: CreditNote + type: object + CreditNotes: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/CreditNote" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Customer: + allOf: + - properties: + addresses: + description: An array of Addresses. + items: + $ref: "#/components/schemas/CompanyDataset/properties/addresses/items" + type: + - array + - "null" + contactName: + description: Name of the main contact for the identified customer. + type: + - string + - "null" + contacts: + description: An array of Contacts. + items: + $ref: "#/components/schemas/Customer/definitions/contact" + type: + - array + - "null" + customerName: + description: Name of the customer as recorded in the accounting system, typically the company name. + type: + - string + - "null" + defaultCurrency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Default currency the transactional data of the customer is recorded in. + emailAddress: + description: Email address the customer can be contacted by. + type: + - string + - "null" + id: + description: Identifier for the customer, unique to the company in the accounting platform. + type: string + metadata: + $ref: "#/components/schemas/Metadata" + phone: + description: Phone number the customer can be contacted by. + type: + - string + - "null" + registrationNumber: + description: Company number. In the UK, this is typically the Companies House company registration number. + type: + - string + - "null" + status: + $ref: "#/components/schemas/Customer/definitions/customerStatus" + description: Current state of the customer. + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + taxNumber: + description: Company tax number. + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + contact: + properties: + address: + $ref: "#/components/schemas/CompanyDataset/properties/addresses/items" + description: An object of Address information. + email: + description: Email of a contact for a customer. + nullable: true + type: string + modifiedDate: + $ref: "#/components/schemas/DateTime" + name: + description: Name of a contact for a customer. + nullable: true + type: string + phone: + description: An array of Phone numbers. + items: + $ref: "#/components/schemas/CompanyDataset/properties/phoneNumbers/items" + nullable: true + type: array + status: + $ref: "#/components/schemas/Customer/definitions/customerStatus" + required: + - status + type: object + customerRef: + properties: + companyName: + description: "`customerName` from the Customer data type" + nullable: true + type: string + id: + description: "`id` from the Customers data type" + minLength: 1 + type: string + required: + - id + type: object + customerStatus: + description: Status of customer. + enum: + - Unknown + - Active + - Archived + type: string + description: | + > View the coverage for customers in the Data coverage explorer. + + ## Overview + + A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). + + Customers' data links to accounts receivable [invoices](https://docs.codat.io/accounting-api#/schemas/Invoice). + required: + - status + title: Customer + type: object + Customers: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Customer" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + DataType: + description: Available Data types + enum: + - accountTransactions + - balanceSheet + - bankAccounts + - bankTransactions + - billCreditNotes + - billPayments + - bills + - cashFlowStatement + - chartOfAccounts + - company + - creditNotes + - customers + - directCosts + - directIncomes + - invoices + - items + - journalEntries + - journals + - paymentMethods + - payments + - profitAndLoss + - purchaseOrders + - salesOrders + - suppliers + - taxRates + - trackingCategories + - transfers + - banking-accountBalances + - banking-accounts + - banking-transactionCategories + - banking-transactions + - commerce-companyInfo + - commerce-customers + - commerce-disputes + - commerce-locations + - commerce-orders + - commerce-paymentMethods + - commerce-payments + - commerce-productCategories + - commerce-products + - commerce-taxComponents + - commerce-transactions + examples: + - invoices + type: string + x-internal: true + Dataset: + properties: + companyId: + format: uuid + type: string + completed: + $ref: "#/components/schemas/DateTime" + nullable: true + connectionId: + format: uuid + type: string + dataType: + type: + - string + - "null" + datasetLogsUrl: + type: + - string + - "null" + errorMessage: + type: + - string + - "null" + id: + format: uuid + type: string + isCompleted: + type: boolean + isErrored: + type: boolean + progress: + format: int32 + type: integer + requested: + $ref: "#/components/schemas/DateTime" + status: + enum: + - Initial + - Queued + - Fetching + - MapQueued + - Mapping + - Complete + - FetchError + - MapError + - InternalError + - ProcessingQueued + - Processing + - ProcessingError + - ValidationQueued + - Validating + - ValidationError + - AuthError + - Cancelled + - NotSupported + - RateLimitError + - PermissionsError + - PrerequisiteNotMet + type: string + validationInformationUrl: + type: + - string + - "null" + required: + - companyId + - connectionId + - id + - isCompleted + - isErrored + - progress + - requested + - status + title: "" + type: object + x-internal: true + DateTime: + description: |- + In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + + ``` + 2020-10-08T22:40:50Z + 2021-01-01T00:00:00 + ``` + + + + When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + + - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` + - Unqualified local time: `2021-11-15T01:00:00` + - UTC time offsets: `2021-11-15T01:00:00-05:00` + + > Time zones + > + > Not all dates from Codat will contain information about time zones. + > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + examples: + - 2022-10-23T00:00:00Z + title: Date time + type: string + DirectCost: + allOf: + - properties: + contactRef: + $ref: "#/components/schemas/Transfer/allOf/0/properties/contactRef" + description: A customer or supplier associated with the direct cost. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the direct cost. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + id: + description: Identifier of the direct cost, unique for the company. + type: string + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date of the direct cost as recorded in the accounting platform.Date of the direct cost as recorded in the accounting platform. + lineItems: + description: An array of line items. + items: + $ref: "#/components/schemas/DirectCost/definitions/directCostLineItem" + type: array + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: A note attached to the direct cost. + type: + - string + - "null" + paymentAllocations: + description: An array of payment allocations. + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items" + type: array + reference: + description: User-friendly reference for the direct cost. + type: + - string + - "null" + subTotal: + description: The total amount of the direct costs, excluding any taxes. + type: number + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + taxAmount: + description: The total amount of tax on the direct costs. + type: number + totalAmount: + description: The amount of the direct costs, inclusive of tax. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + directCostLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Friendly name of the goods or services. + nullable: true + type: string + discountAmount: + description: Discount amount for the line before tax. + nullable: true + type: number + discountPercentage: + description: Discount percentage for the line before tax. + nullable: true + type: number + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the product, service type, or inventory item to which the direct cost is linked. + quantity: + description: |- + Number of units of goods or services received. + + Note: If the platform does not provide this information, the quantity will be mapped as 1. + type: number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax. + nullable: true + type: number + taxAmount: + description: Amount of tax for the line. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the the line item is linked. + totalAmount: + description: Total amount of the line, including tax. + nullable: true + type: number + tracking: + $ref: "#/components/schemas/DirectCost/definitions/tracking" + trackingCategoryRefs: + deprecated: true + description: Collection of categories against which this direct cost is tracked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: |- + Price of each unit of goods or services. + Note: If the platform does not provide this information, the unit amount will be mapped to the total amount. + type: number + required: + - unitAmount + - quantity + type: object + tracking: + additionalProperties: false + properties: + invoiceTo: + description: |- + Links to the underlying record or data type. + + Found on: + + - Journal entries + - Account transactions + - Invoices + - Transfers + properties: + dataType: + description: Name of the 'dataType'. + type: string + id: + description: "'id' of the underlying record or data type." + type: string + type: object + recordRefs: + items: + $ref: "#/components/schemas/DirectCost/definitions/tracking/properties/invoiceTo" + type: array + required: + - recordRefs + title: Invoiceable tracking + type: object + description: |- + > **Language tip:** Direct costs may also be referred to as **Spend transactions**, **Spend money transactions**, or **Payments** in various accounting platforms. + + > View the coverage for direct costs in the Data coverage explorer. + + ## Overview + + Direct costs include: + * Purchasing an item and paying it off at the point of the purchase + * Receiving cash from a refunded item if the refund is made by the supplier + * Withdrawing money from a bank account + * Writing a cheque + + Direct costs is a child data type of [account transactions](https://docs.codat.io/accounting-api#/schemas/AccountTransaction). + required: + - issueDate + - currency + - lineItems + - paymentAllocations + - subTotal + - taxAmount + - totalAmount + title: Direct cost + type: object + DirectCosts: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/DirectCost" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + DirectIncome: + allOf: + - properties: + contactRef: + $ref: "#/components/schemas/Transfer/allOf/0/properties/contactRef" + description: A customer or supplier associated with the direct income. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: The currency of the direct income. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + id: + description: Identifier of the direct income, unique for the company. + type: string + issueDate: + $ref: "#/components/schemas/DateTime" + description: The date of the direct income as recorded in the accounting platform. + lineItems: + description: An array of line items. + items: + $ref: "#/components/schemas/DirectIncome/definitions/directIncomeLineItem" + type: array + metadata: + $ref: "#/components/schemas/Metadata" + note: + type: + - string + - "null" + paymentAllocations: + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items" + type: array + reference: + description: User-friendly reference for the direct income. + type: + - string + - "null" + subTotal: + description: The total amount of the direct incomes, excluding any taxes. + type: number + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + taxAmount: + description: The total amount of tax on the direct incomes. + type: number + totalAmount: + description: The amount of the direct incomes, inclusive of tax. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + directIncomeLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: A user-friendly name of the goods or services. + nullable: true + type: string + discountAmount: + description: Discount amount for the line before tax. + nullable: true + type: number + discountPercentage: + description: Discount percentage for the line before tax. + nullable: true + type: number + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the product, service type, or inventory item to which the direct cost is linked. + quantity: + description: |- + The number of units of goods or services received. + + Note: If the platform does not provide this information, the quantity will be mapped as 1. + type: number + subTotal: + description: The amount of the line, inclusive of discounts, but exclusive of tax. + nullable: true + type: number + taxAmount: + description: |- + The amount of tax for the line. + Note: If the platform does not provide this information, the quantity will be mapped as 0.00. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: The total amount of the line, including tax. + nullable: true + type: number + trackingCategoryRefs: + description: An array of categories against which this direct cost is tracked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: |- + The price of each unit of goods or services. + Note: If the platform does not provide this information, the unit amount will be mapped to the total amount. + type: number + required: + - unitAmount + - quantity + type: object + description: | + > **Language tip:** Direct incomes may also be referred to as **Receive transactions**, **Receive money transactions**, **Sales receipts**, or **Cash sales** in various accounting platforms. + + > View the coverage for direct incomes in the Data coverage explorer. + + ## Overview + + Direct incomes include: + + - Selling an item directly to a contact, and receiving payment at the point of the sale. + - Refunding an item in cash to a contact. + - Depositing money into a bank account. + + Direct incomes is a child data type of [account transactions](https://docs.codat.io/accounting-api#/schemas/AccountTransaction). + required: + - issueDate + - currency + - lineItems + - paymentAllocations + - subTotal + - taxAmount + - totalAmount + title: Direct income + type: object + DirectIncomes: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/DirectIncome" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + HalRef: + properties: + href: + format: uri-reference + type: string + title: Hypertext reference + type: object + x-internal: true + Invoice: + allOf: + - properties: + additionalTaxAmount: + type: number + additionalTaxPercentage: + type: number + amountDue: + description: Amount outstanding on the invoice. + type: number + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the invoice. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + description: Reference to the customer the invoice has been issued to. + discountPercentage: + description: "Percentage rate (from 0 to 100) of discounts applied to the invoice. For example: A 5% discount will return a value of `5`, not `0.05`." + type: + - number + - "null" + dueDate: + $ref: "#/components/schemas/DateTime" + description: Date the customer is due to be paid by. + id: + description: Identifier for the invoice, unique to the company in the accounting platform. + type: string + invoiceNumber: + description: Friendly reference for the invoice. If available, this appears in the file name of invoice attachments. + type: + - string + - "null" + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date of the invoice as recorded in the accounting system. + lineItems: + description: An array of line items. + items: + $ref: "#/components/schemas/Invoice/definitions/invoiceLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information about the invoice. Where possible, Codat links to a data field in the accounting platform that is publicly available. This means that the contents of the note field are included when an invoice is emailed from the accounting platform to the customer. + type: + - string + - "null" + paidOnDate: + $ref: "#/components/schemas/DateTime" + description: Date the invoice was marked as paid in the accounting system. If this field is not available from the accounting software, it is calculated by Codat using associated payments. + paymentAllocations: + description: An array of payment allocations. + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/paymentAllocations/items" + type: + - array + - "null" + salesOrderRefs: + description: List of references to related Sales orders. + items: + type: string + type: + - array + - "null" + status: + $ref: "#/components/schemas/Invoice/definitions/invoiceStatus" + subTotal: + description: Total amount of the invoice excluding any taxes. + type: + - number + - "null" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + totalAmount: + description: Amount of the invoice, inclusive of tax. + type: number + totalDiscount: + description: Numerical value of discounts applied to the invoice. + type: + - number + - "null" + totalTaxAmount: + description: Amount of tax on the invoice. + type: number + withholdingTax: + items: + $ref: "#/components/schemas/Bill/allOf/0/properties/withholdingTax/items" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + invoiceLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Friendly name of the goods or services provided. + nullable: true + type: string + discountAmount: + description: Numerical value of any discounts applied. + nullable: true + type: number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount. + nullable: true + type: number + isDirectIncome: + type: boolean + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the item the line is linked to. + quantity: + description: Number of units of goods or services provided. + type: number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax. + nullable: true + type: number + taxAmount: + description: Amount of tax for the line. + nullable: true + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: Total amount of the line, including tax. When pushing invoices to Xero, the total amount is exclusive of tax to allow automatic calculations if a tax rate or tax amount is not specified. + nullable: true + type: number + tracking: + $ref: "#/components/schemas/CreditNote/definitions/creditNoteLineItem/properties/tracking" + trackingCategoryRefs: + deprecated: true + description: Reference to the tracking categories to which the line item is linked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: Price of each unit of goods or services. + type: number + required: + - unitAmount + - quantity + type: object + invoiceStatus: + description: |- + Current state of the invoice: + + - `Draft` - Invoice hasn't been submitted to the supplier. It may be in a pending state or is scheduled for future submission, for example by email. + - `Submitted` - Invoice is no longer a draft. It has been processed and, or, sent to the customer. In this state, it will impact the ledger. It also has no payments made against it (amountDue == totalAmount). + - `PartiallyPaid` - The balance paid against the invoice is positive, but less than the total invoice amount (0 < amountDue < totalAmount). + - `Paid` - Invoice is paid in full. This includes if the invoice has been credited or overpaid (amountDue == 0). + - `Void` - An invoice can become Void when it's deleted, refunded, written off, or cancelled. A voided invoice may still be PartiallyPaid, and so all outstanding amounts on voided invoices are removed from the accounts receivable account. + enum: + - Unknown + - Draft + - Submitted + - PartiallyPaid + - Paid + - Void + type: string + description: |- + > View the coverage for invoices in the Data coverage explorer. + + ## Overview + + An invoice is an itemized record of goods sold or services provided to a [customer](https://docs.codat.io/accounting-api#/schemas/Customer). + + In Codat, an invoice contains details of: + + - The timeline of the invoice—when it was raised, marked as paid, last edited, and so on. + - How much the invoice is for, what portion of the invoice is tax or discounts, and what currency the amounts are represented in. + - Who the invoice has been raised to; the _customer_. + - The breakdown of what the invoice is for; the _line items_. + - Any [payments](https://docs.codat.io/accounting-api#/schemas/Payment) assigned to the invoice; the _payment allocations_. + + > **Invoices or bills?** + > + > In Codat, invoices represent accounts receivable only. For accounts payable invoices, see [Bills](https://docs.codat.io/accounting-api#/schemas/Bill). + + > **Invoice PDF downloads** + > + > You can download a PDF version of an invoice for supported integrations. + > + > The filename will be invoice-{number}.pdf. + + > **Referencing an invoice in Sage 50 and ClearBooks** + > + > In Sage 50 and ClearBooks, you may prefer to use the **invoiceNumber** to identify an invoice rather than the invoice **id**. Each time a draft invoice is submitted or printed, the draft **id** becomes void and a submitted invoice with a new **id** exists in its place. In both platforms, the **invoiceNumber** should remain the same. + required: + - issueDate + - totalTaxAmount + - totalAmount + - amountDue + - status + title: Invoice + type: object + Invoices: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Invoice" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Item: + allOf: + - properties: + billItem: + $ref: "#/components/schemas/Item/definitions/billItem" + code: + description: Friendly reference for the item. + type: + - string + - "null" + id: + description: Identifier for the item that is unique to a company in the accounting platform. + type: string + invoiceItem: + $ref: "#/components/schemas/Item/definitions/invoiceItem" + isBillItem: + description: Whether you can use this item for bills. + type: boolean + isInvoiceItem: + description: Whether you can use this item for invoices. + type: boolean + itemStatus: + $ref: "#/components/schemas/Item/definitions/itemStatus" + metadata: + $ref: "#/components/schemas/Metadata" + name: + description: Name of the item in the accounting platform. + type: + - string + - "null" + type: + $ref: "#/components/schemas/Item/definitions/itemType" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + billItem: + description: Item details that are only for bills. + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference of the account to which the item is linked. + description: + description: Short description of the product or service that has been bought by the customer. + nullable: true + type: string + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference of the tax rate to which the item is linked. + unitPrice: + description: Unit price of the product or service. + nullable: true + type: number + type: object + invoiceItem: + description: Item details that are only for bills. + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference of the account to which the item is linked. + description: + description: Short description of the product or service that has been bought by the customer. + nullable: true + type: string + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + unitPrice: + description: Unit price of the product or service. + nullable: true + type: number + type: object + itemRef: + properties: + id: + description: Unique identifier for the item in the accounting platform. + minLength: 1 + type: string + name: + description: Name of the item in the accounting platform. + nullable: true + type: string + required: + - id + title: Item reference + type: object + itemStatus: + description: |- + Current state of the item, either: + + - `Active`: Available for use + - `Archived`: Unavailable + - `Unknown` + + Due to a [limitation in Xero's API](https://docs.codat.io/integrations/accounting/xero/xero-faq#why-do-all-of-my-items-from-xero-have-their-status-as-unknown), all items from Xero are mapped as `Unknown`. + enum: + - Unknown + - Active + - Archived + type: string + itemType: + type: + description: Type of the item. + enum: + - Unknown + - Inventory + - NonInventory + - Service + type: string + description: | + > View the coverage for items in the Data coverage explorer. + + ## Overview + + **Items** allow your customers to save and track details of the products and services that they buy and sell. + required: + - itemStatus + - type + - isBillItem + - isInvoiceItem + title: Item + type: object + Items: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Item" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Journal: + allOf: + - properties: + createdOn: + $ref: "#/components/schemas/DateTime" + description: Journal creation date. + hasChildren: + description: If the journal has child journals, this value is true. If it doesn’t, it is false. + type: boolean + id: + description: Journal ID. + type: string + journalCode: + description: Native journal number or code. + type: + - string + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + name: + description: |- + Journal name. + The maximum length for a journal name is 256 characters. All characters above that number will be truncated. + type: + - string + - "null" + parentId: + description: |- + Parent journal ID. + If the journal is a parent journal, this value is not present. + type: + - string + - "null" + status: + $ref: "#/components/schemas/Journal/definitions/journalStatus" + type: + description: The type of the journal. + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + journalRef: + additionalProperties: false + description: Links journal entries to the relevant journal in accounting integrations that use multi-book accounting (multiple journals). + properties: + id: + description: GUID of the underlying journal. + minLength: 1 + type: string + name: + description: Name of journal + maxLength: 256 + nullable: true + type: string + required: + - id + title: Journal reference + type: object + journalStatus: + description: Current journal status. + enum: + - Unknown + - Active + - Archived + type: string + description: | + > **Language tip:** For line items, or individual transactions, of a company's financial documents, refer to the [Journal entries](https://docs.codat.io/accounting-api#/schemas/JournalEntry) data type + + > View the coverage for journals in the Data coverage explorer. + + ## Overview + + In accounting software, journals are used to record all the financial transactions of a company. Each transaction in a journal is represented by a separate [journal entry](https://docs.codat.io/accounting-api#/schemas/JournalEntry). These entries are used to create the general ledger, which is then used to create the financial statements of a business. + + When a company records all their transactions in a single journal, it can become large and difficult to maintain and track. This is why large companies often use multiple journals (also known as subjournals) to categorize and manage journal entries. + + Such journals can be divided into two categories: + + - Special journals: journals used to record specific types of transactions; for example, a purchases journal, a sales journal, or a cash management journal. + - General journals: journals used to record transactions that fall outside the scope of the special journals. + + Multiple journals or subjournals are used in the following Codat integrations: + + - [Sage Intacct](https://docs.codat.io/integrations/accounting/sage-intacct/accounting-sage-intacct) (mandatory) + - [Exact Online](https://docs.codat.io/integrations/accounting/exact-online/accounting-exact-online) (mandatory) + - [Oracle NetSuite](https://docs.codat.io/integrations/accounting/netsuite/accounting-netsuite) (optional) + + > When pushing journal entries to an accounting platform that doesn’t support multiple journals (multi-book accounting), the entries will be linked to the platform-generic journal. The Journals data type will only include one object. + title: Journal + type: object + JournalEntries: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/JournalEntry" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + JournalEntry: + allOf: + - properties: + createdOn: + $ref: "#/components/schemas/DateTime" + description: Date on which the journal was created in the accounting platform. + description: + description: Optional description of the journal entry. + type: + - string + - "null" + id: + description: Unique identifier of the journal entry for the company in the accounting platform. + type: string + journalLines: + description: An array of journal lines. + items: + $ref: "#/components/schemas/JournalEntry/definitions/journalLine" + type: + - array + - "null" + journalRef: + $ref: "#/components/schemas/Journal/definitions/journalRef" + metadata: + $ref: "#/components/schemas/Metadata" + postedOn: + $ref: "#/components/schemas/DateTime" + description: |- + Date on which the journal entry was posted to the accounting platform, and had an impact on the general ledger. This may be different from the creation date. + + For example, a user creates a journal entry on Monday and saves it as draft, which has no impact on the general ledger. On Thursday, they return to the entry and post it. + + The **createdOn** date shows as Monday. + The **postedOn** date shows as Thursday. + Journal entries can also be backdated, so the **postedOn** date may be earlier than the **createdOn** date. + recordRef: + $ref: "#/components/schemas/DirectCost/definitions/tracking/properties/invoiceTo" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + updatedOn: + $ref: "#/components/schemas/DateTime" + description: Date on which the journal was last updated in the accounting platform. + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + journalLine: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + currency: + description: Currency for the journal line item. + nullable: true + type: string + description: + description: Description of the journal line item. + nullable: true + type: string + netAmount: + description: Amount for the journal line. Debit entries are considered positive, and credit entries are considered negative. + type: number + tracking: + $ref: "#/components/schemas/SalesOrder/definitions/salesOrderLineItem/properties/tracking" + description: List of record refs associated with the tracking information for the line (eg to a Tracking Category, or customer etc.) + required: + - netAmount + type: object + description: |- + > **Language tip:** For the top-level record of a company's financial transactions, refer to the [Journals](https://docs.codat.io/accounting-api#/schemas/Journal) data type + + > View the coverage for journal entries in the Data coverage explorer. + + ## Overview + + A journal entry report shows the entries made in a company's general ledger, or [accounts](https://docs.codat.io/accounting-api#/schemas/Account), when transactions are approved. The journal line items for each journal entry should balance. + + A journal entry line item is a single transaction line on the journal entry. For example: + + - When a journal entry is recording a receipt of cash, the credit to accounts receivable and the debit to cash are separate line items. + - When a company needs to recognise revenue from an annual contract on a monthly basis, on receipt of cash for month one, they make a debit to deferred income and a credit to revenue. + + In Codat a journal entry contains details of: + + - The date on which the entry was created and posted. + - Itemised lines, including amounts and currency. + - A reference to the associated accounts. + - A reference to the underlying record. For example, the invoice, bill, or other data type that triggered the posting of the journal entry to the general ledger. + + > **Pushing journal entries** + > Codat only supports journal entries in the base currency of the company that are pushed into accounts denominated in the same base currency. + title: Journal entry + type: object + Journals: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Journal" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Links: + examples: + - current: + href: /companies/{id}/data/{dataType}?page=1&pageSize=10 + self: + href: /companies/{id}/data/{dataType} + properties: + current: + $ref: "#/components/schemas/HalRef" + next: + $ref: "#/components/schemas/HalRef" + previous: + $ref: "#/components/schemas/HalRef" + self: + $ref: "#/components/schemas/HalRef" + required: + - self + - current + type: object + x-internal: true + Metadata: + properties: + isDeleted: + description: Indicates whether the record has been deleted in the third-party system this record originated from. + type: + - boolean + - "null" + type: object + x-internal: true + ModifiedDates: + allOf: + - properties: + modifiedDate: + $ref: "#/components/schemas/DateTime" + description: The date on which this record was last modified in Codat. + title: ModifiedDate + type: object + x-internal: true + - properties: + sourceModifiedDate: + $ref: "#/components/schemas/DateTime" + description: The date on which this record was last modified in the originating system + title: Source Modified Date + type: object + x-internal: true + x-internal: true + PagingInfo: + examples: + - _links: + current: + href: /companies/{id}/data/{dataType}?page=1&pageSize=10 + pageNumber: 1 + pageSize: 10 + self: + href: /companies/{id}/data/{dataType} + totalResults: 1 + properties: + _links: + $ref: "#/components/schemas/Links" + pageNumber: + type: integer + pageSize: + type: integer + totalResults: + type: integer + required: + - pageNumber + - pageSize + - totalResults + - _links + type: object + x-internal: true + Payment: + allOf: + - properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Account the payment is recorded against in the accounting platform. + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: ISO currency code recorded for the payment in the accounting platform. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + description: Customer the payment is recorded against in the accounting platform. + date: + $ref: "#/components/schemas/DateTime" + description: Date the payment was recorded in the accounting software. + id: + description: Identifier for the payment, unique to the company in the accounting platform. + type: string + lines: + description: An array of payment lines. + items: + $ref: "#/components/schemas/Payment/definitions/paymentLine" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information associated with the payment. + type: + - string + - "null" + paymentMethodRef: + $ref: "#/components/schemas/PaymentMethod/definitions/paymentMethodRef" + description: The Payment Method to which the payment is linked in the accounting platform. + reference: + description: Friendly reference for the payment. + type: + - string + - "null" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + totalAmount: + description: Amount of the payment in the payment currency. This value should never change and represents the amount of money paid into the customer's account. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + paymentLine: + properties: + allocatedOnDate: + $ref: "#/components/schemas/DateTime" + description: The date the payment was allocated. + amount: + description: Amount in the payment currency. + type: number + links: + items: + $ref: "#/components/schemas/Payment/definitions/paymentLineLink" + nullable: true + type: array + required: + - amount + title: Payment Line + type: object + paymentLineLink: + additionalProperties: false + properties: + amount: + description: |- + Amount by which the balance of the linked entity is altered, in the currency of the linked entity. + A negative link amount _reduces_ the outstanding amount on the accounts receivable account. + A positive link amount _increases_ the outstanding amount on the accounts receivable account. + nullable: true + type: number + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + id: + description: Unique identifier of the transaction represented by the link. + type: string + type: + $ref: "#/components/schemas/Payment/definitions/paymentLinkType" + required: + - type + title: Payment Line Link + type: object + paymentLinkType: + description: |- + Types of payment line links, either: + `Unknown` + `Unlinked` - Not used + `Invoice` - ID refers to the invoice + `CreditNote` - ID refers to the credit note + `Refund` - ID refers to the sibling payment + `Payment` - ID refers to the sibling payment + `PaymentOnAccount` - ID refers to the customer + `Other` - ID refers to the customer + `Manual Journal` + `Discount` - ID refers to the payment + enum: + - Unknown + - Unlinked + - Invoice + - CreditNote + - Other + - Refund + - Payment + - PaymentOnAccount + - ManualJournal + - Discount + title: Payment Link Type + type: string + description: |- + > **Payments or bill payments?** + > + > In Codat, payments represent accounts receivable only. For accounts payable, see [bill payments](https://docs.codat.io/accounting-api#/schemas/BillPayment). These include [bills](https://docs.codat.io/accounting-api#/schemas/Bill) and credit notes against bills. + + > View the coverage for payments in the Data coverage explorer. + + ## Overview + + Payments include all accounts receivable transaction data. This includes [invoices](https://docs.codat.io/accounting-api#/schemas/Invoice) and [credit notes](https://docs.codat.io/accounting-api#/schemas/CreditNote). + + A payment in Codat usually represents an allocation of money within any customer accounts receivable account. This includes, but is not strictly limited to: + + - A payment made against an invoice, like a credit card, cheque, or cash payment. + - An allocation of a customer's credit note, either to an invoice or maybe a refund. + - A payment made directly to that accounts receivable account. This might be an overpayment or a prepayment. It might also be the refund of a payment made directly to an accounts receivable account. + + Depending on the payments allowed by the underlying accounting package, some payment types may be combined. Please see the example for more details. + + In Codat, a payment contains details of: + + - When the payment was recorded in the accounting system. + - How much it is for and in what currency that amount is in. + - Who the payment was _paid by_ – the _customer_. + - The payment method used. + - The breakdown of the types of payments – the _line items_. + + Payments is a child data type of [account transactions](https://docs.codat.io/accounting-api#/schemas/AccountTransaction). + + ## Payment types + + ## Payment of an invoice + + A payment paying a single invoice has one entry in its `lines` array. This **line** has the following properties: + + - An _amount_ that indicates the amount of the invoice that was paid. This is always positive. + - A **links** array containing one element with the following properties: + - A **type** that indicates the type of **link**, in this case an `Invoice`. + - An **id** that contains the ID of the invoice that was paid. + - An **amount** for the link. The sum of the **line.amount** and the **links.amount** must equal `0`. + + The **amount** field on the **line** equals the **totalAmount** on the payment. + + ## Payment of multiple invoices + + A single payment can pay multiple invoices. This can be represented in one of two formats depending on how the customer keeps their books: + + - The payment has multiple entries in its **lines** array, one for each invoice that is paid. Each line follows the example and rules described in [Payment of an invoice](#payment-of-an-invoice). + - The payment has a line with multiple links to each invoice. This occurs when the proportion of the original payment allocated to each invoice is not available. + + Each **line** has the same properties as those described in [Payment of an invoice](#payment-of-an-invoice), with the **amount** indicating how much of the payment was allocated to the invoice. The sum of line amounts equals the **totalAmount** on the payment. + + ## Payments and refunds on account + + A payment on account, that is a payment that doesn’t pay a specific invoice, has one entry in its lines array. The **line** has the following properties: + + - A **totalAmount** that indicates the amount paid by a customer or refunded to them by a company. A payment to the customer is always negative. A refund is always positive. + - A **links** array containing one element with the following properties: + - A **type** that indicates the type of link. For a payment this is `PaymentOnAccount`. For a refund this is `Refund`. + - The **id** containing the ID of the customer. + - The **amount** for the link is `0` – the **totalAmount** _or_ the amount of the payment or refund. + + It is possible to have a payment that is part _on account_ and part _allocated_ to an invoice. Each line should follow the examples above. + + ## Using a credit note to pay an invoice + + The payment of an invoice using a credit note has one entry in its **lines** array. This **line** has the following properties: + + - An **amount** that indicates the amount of money moved, which in this case is `0`, as the credit note and invoice allocation must balance each other. + - A **links** array containing two elements: + - The first **link** has: + - A **type** that indicates the type of **link**, in this case an `Invoice`. + - An **id** that contains the ID of the invoice that was paid. + - The second **link** has: + - A **type** that indicates the type of **link**, in this case a `CreditNote`. + - An **id** that contains the ID of the credit note used by this payment. + + The **amount** field on the **line** equals the **totalAmount** on the payment. + + ## Refunding a credit note + + A payment refunding a credit note has one entry in its **lines** array. This **line** has the following properties: + + - An **amount** that indicates the amount of the credit note that was refunded. This is always negative for a refund. + - A **links** array that contains one element with the following properties: + - A **type** that indicates the type of **link**, in this case a `CreditNote`. + - An **id** that contains the ID of the credit note that was refunded. + + The **totalAmount** field on the payment equals the **amount** field of the **line**. These are both negative, as this is money leaving accounts receivable. + + ## Refunding a payment + + If a payment is refunded, for example, if a customer overpaid an invoice and the overpayment is returned to the customer, there are two payment records: + + - One for the incoming over payment. + - Another for the outgoing refund. + + The payment issuing the refund has a negative **totalAmount**. This payment also has one entry in its lines array with the following properties: + + - An **amount** that indicates the amount that was refunded. This is always negative. + - A **links** array that contains one element with the following properties: + - A **type** that indicates the type of **link**, in this case a `Payment`. + - An **id** that contains the ID of the payment that was refunded. + + The **amount** field on the **line** equals the **totalAmount** on the payment and is negative, as this is money leaving accounts receivable. + + The payment that was refunded has a line where the **amount** is positive and the type of the link is `Refund`. This payment may have several entries in its **lines** array if it was used to partly pay an invoice. + + For example: A £1,050 payment on a £1,000 invoice with a refund of £50 has two lines: + + - One for £1,000 linked to the invoice that was paid. + - Another for £50 linked to the payment that refunded the overpayment with a** type** of `Refund` and an ID that corresponds to the payment. + + The **line** linked to the payment has the following properties: + + - An **amount** that indicates the amount that was refunded. This is positive as its money that was added to accounts receivable. It's balanced out by the negative amount of the refund. + - A **links** array containing one element with the following properties: + - A **type** that indicates the type of **link**, in this case a `Refund`. + - An **id** that contains the ID of the payment that refunded this line. + + > **Support for linked payments** + > + > Not all accounting packages support linking payments in this way. In some platforms, you may see a payment on account and a refund on account. + + ## Foreign currencies + + There are two types of currency rate that are included in the payments data type: + + Payment currency rate: + + - Base currency of the accounts receivable account. + - Foreign currency of the payment. + + Payment line link currency rate: + + - Base currency of the item the link represents. + - Foreign currency of the payment. + + These two rates allow the calculation of currency loss or gain for any of the transactions affected by the payment lines. The second rate is used when a payment is applied to an item in a currency that doesn't match either: + + - The base currency for the accounts receivable account. + - The currency of the item. + + ```json title="Currency rate example" + { + "id": "123", + "note": "" + "totalAmount": 99.99, + "currency": "GBP", + "lines": [ + { + "amount": 99.99, + "links": [ + { + "type": "Invoice", + "id": "178", + "amount": -50, + "currencyRate": 1.9998, + } + ] + } + ] + } + ``` + + + + ## Example data + + > **Object properties** + > + > For the sake of brevity, the examples here may omit properties from objects. For the full object definition, see [Payments](https://api.codat.io/swagger/index.html#/Payments). + + ## Simple examples + + ```json title="Payment for invoice" + { + "totalAmount": 1000, + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + } + ] + } + ] + } + ``` + + + + ```json title="Allocation of credit note" + { + "totalAmount": 0, + "lines": [ + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + ```json title="Payment of invoice and payment on account" + { + "totalAmount": 2000, + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "PaymentOnAccount", + "id" : "y", + "amount" : -1000 + } + ] + } + ] + } + ``` + + + + ```json title="Refund of credit note" + { + "totalAmount": -1000, + "lines": [ + { + "amount" : -1000, + "links" : [ + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + ```json title="Refund on accounts receivable account" + { + "totalAmount": -1000, + "lines": [ + { + "amount" : -1000, + "links" : [ + { + "type" : "PaymentOnAccount", + "id" : "y", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + ```json title="Linked refund on accounts receivable account" + { + "id" : "payment-001", + "totalAmount": 1000, + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Refund", + "id" : "refund-001", + "amount" : -1000 + } + ] + } + ] + } + { + "id" : "refund-001", + "totalAmount": -1000, + "lines": [ + { + "amount" : -1000, + "links" : [ + { + "type" : "Payment", + "id" : "payment-001", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + ```json title="Using a credit note and cash to pay an invoice" + { + "totalAmount": 250, + "lines": [ + { + "amount": 0, + "links": [ + { + "type": "Invoice", + "id": "x", + "amount": -750 + }, + { + "type": "CreditNote", + "id": "y", + "amount": 750 + } + ] + }, + { + "amount": 250, + "links": [ + { + "type": "Invoice", + "id": "x", + "amount": -250 + } + ] + } + ] + } + ``` + + + + ## Complex examples + + ```json title="Use two credit notes and 1000 in to "bank" (cash, cheque etc.) to pay invoice" + { + "totalAmount": 1000, + "lines": [ + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + } + ] + }, + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "z", + "amount" : 1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + } + ] + } + ] + } + ``` + + + + ```json title="Pay an invoice with two credit notes and cash, with 1000 left 'on account'" + { + "totalAmount": 2000, + "lines": [ + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + } + ] + }, + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "z", + "amount" : 1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "PaymentOnAccount", + "id" : "customer-001", + "amount" : -1000 + } + ] + } + ] + } + ``` + + + + ```json title="Two credit notes pay two invoices with no allocation amount specified" + { + "totalAmount": 0, + "lines": [ + { + "amount" : 0, + "links" : [ + { + "type" : "Invoice", + "id" : "w", + "amount" : -1000 + }, + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + }, + { + "type" : "CreditNote", + "id" : "z", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + ```json title="Two credit notes and cash pay three invoices with no allocation amount specified, and refund cash" + { + "totalAmount": 2000, + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "w", + "amount" : -1000 + }, + { + "type" : "Invoice", + "id" : "x", + "amount" : -1000 + }, + { + "type" : "Invoice", + "id" : "u", + "amount" : -1000 + }, + { + "type" : "CreditNote", + "id" : "y", + "amount" : 1000 + }, + { + "type" : "CreditNote", + "id" : "z", + "amount" : 1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "Refund", + "id" : "refund-001", + "amount" : -1000 + } + ] + } + ] + } + { + "id" : "refund-001", + "totalAmount": -1000, + "lines": [ + { + "amount" : -1000, + "links" : [ + { + "type" : "Payment", + "id" : "payment-001", + "amount" : 1000 + } + ] + } + ] + } + ``` + + + + In this example, a payment on account is used to pay the same invoice in January and again in February. + + ```json title="January" + { + "id": "001", + "totalAmount": 5000, + "date" : "1901-01-01", + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "Invoice-x", + "amount" : -1000 + } + ] + }, + { + "amount" : 4000, + "links" : [ + { + "type" : "PaymentOnAccount", + "id" : "PaymentOnAccount-y", + "amount" : -4000 + } + ] + } + ] + } + ``` + + + + ```json title="February" + { + "id": "001", + "totalAmount": 5000, + "date" : "1901-02-01", + "lines": [ + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "Invoice-x", + "amount" : -1000 + } + ] + }, + { + "amount" : 1000, + "links" : [ + { + "type" : "Invoice", + "id" : "Invoice-y", + "amount" : -1000 + } + ] + }, + { + "amount" : 3000, + "links" : [ + { + "type" : "PaymentOnAccount", + "id" : "PaymentOnAccount-y", + "amount" : -3000 + } + ] + } + ] + } + ``` + + + + ```json title="Two credit notes and some cash pay two invoices with no allocations specified" + { + "totalAmount": 500, + "lines": [ + { + "amount": 500, + "links": [{ + "type": "Invoice", + "id": "a", + "amount": -1000 + }, { + "type": "Invoice", + "id": "b", + "amount": -1000 + }, { + "type": "CreditNote", + "id": "y", + "amount": 750 + },{ + "type": "CreditNote", + "id": "z", + "amount": 750 + } + ] + } + ] + } + ``` + required: + - date + title: Payment + type: object + PaymentMethod: + allOf: + - properties: + id: + description: Unique identifier for the payment method. + type: string + metadata: + $ref: "#/components/schemas/Metadata" + name: + description: Name of the payment method. + type: + - string + - "null" + status: + $ref: "#/components/schemas/PaymentMethod/definitions/paymentMethodStatus" + type: + $ref: "#/components/schemas/PaymentMethod/definitions/paymentMethodType" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + paymentMethodRef: + properties: + id: + description: "`id` from the Payment Methods data type" + type: string + name: + description: "`name` from the Payment Methods data type" + nullable: true + type: string + type: object + paymentMethodStatus: + description: Status of the Payment Method. + enum: + - Unknown + - Active + - Archived + type: string + paymentMethodType: + description: Method of payment. + enum: + - Unknown + - Cash + - Check + - CreditCard + - DebitCard + - BankTransfer + - Other + type: string + description: |- + > View the coverage for payment methods in the Data coverage explorer. + + ## Overview + + A Payment Method represents the payment method(s) used to pay a Bill. Payment Methods are referenced on [Bill Payments](https://docs.codat.io/accounting-api#/schemas/BillPayment) and [Payments](https://docs.codat.io/accounting-api#/schemas/Payment). + title: Payment method + type: object + PaymentMethods: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Bill" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Payments: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Payments" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + ProfitAndLossReport: + definitions: + profitAndLossReport: + additionalProperties: false + properties: + costOfSales: + $ref: "#/components/schemas/ReportLine" + description: ReportLine items for cost of sales in the given date range. + expenses: + $ref: "#/components/schemas/ReportLine" + description: ReportLine items for expenses in the given date range. + fromDate: + $ref: "#/components/schemas/DateTime" + description: Date from which the report data begins. + grossProfit: + description: Gross profit of the company in the given date range. + type: number + income: + $ref: "#/components/schemas/ReportLine" + description: ReportLine items for income in the given date range. + netOperatingProfit: + description: Net operating profit of the company in the given date range. + type: number + netOtherIncome: + description: Net other income of the company in the given date range. + type: number + netProfit: + description: Net profit of the company in the given date range. + type: number + otherExpenses: + $ref: "#/components/schemas/ReportLine" + description: ReportLine items for other expenses in the given date range. + otherIncome: + $ref: "#/components/schemas/ReportLine" + description: ReportLine items for other income in the given date range. + toDate: + $ref: "#/components/schemas/DateTime" + description: Date on which the report data ends. + required: + - grossProfit + - netOperatingProfit + - netOtherIncome + - netProfit + type: object + reportBasis: + description: The basis of a report. + enum: + - Unknown + - Accrual + - Cash + type: string + description: |- + > **Language tip:** Profit and loss statement is also referred to as **income statement** under US GAAP (Generally Accepted Accounting Principles). + + > View the coverage for profit and loss in the Data coverage explorer. + + ## Overview + + The purpose of a profit and loss report is to present the financial performance of a company over a specified time period. + + A profit and loss report shows a company's total income and expenses for a specified period of time and whether a profit or loss has been made. + + > **Profit and loss or balance sheet?** + > Profit and loss reports summarise the total revenue, expenses, and profit or loss over a specified time period. A balance sheet report presents all assets, liability, and equity for a given date. + + + **Structure of this report** + This report will reflect the structure and line descriptions that the business has set in their own accounting platform. + + **History** + By default, Codat pulls (up to) 24 months of profit and loss history for a company. You can adjust this to fetch more history, where available, by updating the `monthsToSync` value for `profitAndLoss` on the [data type settings endpoint](https://docs.codat.io/codat-api#/operations/post-profile-syncSettings). + + **Want to pull this in a standardised structure?** + Our [Enhanced Financials](https://docs.codat.io/assess/reports/enhanced-financials/financials) endpoints provide the same report under standardized headings, allowing you to pull it in the same format for all of your business customers. + properties: + currency: + description: Base currency of the company in which the profit and loss report is presented. + minLength: 1 + type: string + earliestAvailableMonth: + $ref: "#/components/schemas/DateTime" + description: Earliest available monthly report data. + mostRecentAvailableMonth: + $ref: "#/components/schemas/DateTime" + description: Most recent available monthly report data. + reportBasis: + $ref: "#/components/schemas/ProfitAndLossReport/definitions/reportBasis" + reports: + description: An array of profit and loss reports. + items: + $ref: "#/components/schemas/ProfitAndLossReport/definitions/profitAndLossReport" + type: array + required: + - reports + - reportBasis + - currency + title: Profit and loss report + type: object + ProjectRef: + properties: + id: + minLength: 1 + type: string + name: + type: + - string + - "null" + required: + - id + type: object + x-internal: true + PurchaseOrder: + allOf: + - properties: + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the purchase order. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + deliveryDate: + $ref: "#/components/schemas/DateTime" + description: Actual delivery date for any goods that have been ordered. + nullable: true + expectedDeliveryDate: + $ref: "#/components/schemas/DateTime" + description: Expected delivery date for any goods that have been ordered. + nullable: true + id: + description: Identifier for the purchase order, unique for the company in the accounting platform. + type: string + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date of the purchase order as recorded in the accounting platform. + lineItems: + description: Array of line items. + items: + $ref: "#/components/schemas/PurchaseOrder/definitions/purchaseOrderLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information associated with the purchase order. + type: + - string + - "null" + paymentDueDate: + $ref: "#/components/schemas/DateTime" + description: Date the supplier is due to be paid. + nullable: true + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform. + type: + - string + - "null" + shipTo: + $ref: "#/components/schemas/SalesOrder/allOf/0/properties/shipTo" + description: Delivery details for any goods that have been ordered. + status: + $ref: "#/components/schemas/PurchaseOrder/definitions/purchaseOrderStatus" + subTotal: + description: Total amount of the purchase order, including discounts but excluding tax. + type: number + supplierRef: + $ref: "#/components/schemas/Supplier/definitions/supplierRef" + description: Supplier that the purchase order is recorded against in the accounting system. + totalAmount: + description: Total amount of the purchase order, including discounts and tax. + type: number + totalDiscount: + description: Total value of any discounts applied to the purchase order. + type: number + totalTaxAmount: + description: |- + + Total amount of tax included in the purchase order. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + purchaseOrderLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Description of the goods / services that have been ordered. + nullable: true + type: string + discountAmount: + description: Value of any discounts applied. + type: number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount. + type: number + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the product or inventory item to which the line item is linked. + quantity: + description: Number of units that have been ordered. + type: number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax. + type: number + taxAmount: + description: Amount of tax for the line. + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: Total amount of the line, inclusive of discounts and tax. + type: number + trackingCategoryRefs: + description: Reference to the tracking categories to which the line item is linked. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + nullable: true + type: array + unitAmount: + description: Price of each unit. + type: number + type: object + purchaseOrderRef: + additionalProperties: false + properties: + id: + description: Identifier for the purchase order, unique for the company in the accounting platform. + type: string + purchaseOrderNumber: + description: Friendly reference for the purchase order, commonly generated by the accounting platform. + nullable: true + type: string + title: Purchase order Reference + type: object + purchaseOrderStatus: + description: Current state of the purchase order + enum: + - Unknown + - Draft + - Open + - Closed + - Void + type: string + description: |- + > View the coverage for purchase orders in the Data coverage explorer. + + ## Overview + + Purchase orders represent a business's intent to purchase goods or services from a supplier and normally include information such as expected delivery dates and shipping details. + + This information can be used to provide visibility on a business's expected payables and to track a purchase through the full procurement process. + examples: + - currency: GBP + currencyRate: 1 + deliveryDate: 2021-02-02T00:00:00Z + expectedDeliveryDate: 2021-01-29T00:00:00Z + id: 7e2380af-b51f-4393-92d7-6ff0382da26c + issueDate: 2020-10-24T00:00:00Z + lineItems: + - accountRef: + id: 13931cbf-ea06-4d6e-9538-a8457fa66011 + name: Cost of Goods Sold + description: Electric Eye purchase + discountAmount: 0 + discountPercentage: 0 + itemRef: + id: 9409d23d-1011-432e-98a4-591fcd8d5404 + name: ACME Electric Eye + quantity: 9 + subTotal: 1035 + taxAmount: 103.5 + taxRateRef: + id: 6c88aff3-7cb9-4980-a3d3-443e72e02498 + name: ACME Sales Tax (10%) + totalAmount: 1138.5 + trackingCategoryRefs: [] + unitAmount: 115 + modifiedDate: 2020-11-17T21:11:20Z + note: purchaseorder with 1 line items, totalling 1138.5 + paymentDueDate: 2021-09-13T00:00:00Z + purchaseOrderNumber: "89443280" + shipTo: + address: + city: Dallas + country: USA + line1: 1 Carolyns Circle + line2: "" + postalCode: "511210" + region: Texas + type: Billing + contact: + email: sales@carltoninnov.com + name: Carlton Innovations + phone: "" + sourceModifiedDate: 2020-10-25T06:37:33Z + status: Closed + subTotal: 1035 + supplierRef: + id: 7ff6add1-b0e7-496f-b655-48e20c8fdb2e + supplierName: Carlton Innovations + totalAmount: 1138.5 + totalDiscount: 0 + totalTaxAmount: 103.5 + title: Purchase order + type: object + PurchaseOrders: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/PurchaseOrder" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + PushOperationSummary: + definitions: + pushChangeType: + enum: + - Unknown + - Created + - Modified + - Deleted + - AttachmentUploaded + title: Push change type + type: string + pushOperationChange: + properties: + attachmentId: + nullable: true + type: string + recordRef: + $ref: "#/components/schemas/PushOperationSummary/definitions/pushOperationRef" + type: + $ref: "#/components/schemas/PushOperationSummary/definitions/pushChangeType" + type: object + pushOperationRef: + additionalProperties: false + properties: + dataType: + $ref: "#/components/schemas/DataType" + nullable: true + id: + type: string + title: Push operation reference + type: object + x-internal: true + pushOperationStatus: + description: The status of the push operation. + enum: + - Pending + - Failed + - Success + - TimedOut + title: Push operation status + type: string + validation: + description: A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + properties: + errors: + items: + $ref: "#/components/schemas/PushOperationSummary/definitions/validationItem" + nullable: true + type: array + warnings: + items: + $ref: "#/components/schemas/PushOperationSummary/definitions/validationItem" + nullable: true + type: array + title: Validation + type: object + validationItem: + additionalProperties: false + properties: + itemId: + nullable: true + type: string + message: + nullable: true + type: string + validatorName: + nullable: true + type: string + title: Validation item + type: object + properties: + changes: + items: + $ref: "#/components/schemas/PushOperationSummary/definitions/pushOperationChange" + type: + - array + - "null" + companyId: + $ref: "#/components/parameters/companyId/schema" + completedOnUtc: + $ref: "#/components/schemas/DateTime" + description: The datetime when the push was completed, null if Pending. + dataConnectionKey: + $ref: "#/components/parameters/connectionId/schema" + dataType: + $ref: "#/components/schemas/DataType" + description: The type of data being pushed, eg invoices, customers. + nullable: true + errorMessage: + type: + - string + - "null" + pushOperationKey: + description: A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted. + format: uuid + type: string + requestedOnUtc: + $ref: "#/components/schemas/DateTime" + description: The datetime when the push was requested. + status: + $ref: "#/components/schemas/PushOperationSummary/definitions/pushOperationStatus" + statusCode: + type: integer + timeoutInMinutes: + format: int32 + type: + - integer + - "null" + timeoutInSeconds: + deprecated: true + format: int32 + type: + - integer + - "null" + validation: + $ref: "#/components/schemas/PushOperationSummary/definitions/validation" + required: + - companyId + - pushOperationKey + - dataConnectionKey + - requestedOnUtc + - status + - statusCode + type: object + x-internal: true + PushOption: + definitions: + pushFieldValidation: + additionalProperties: false + properties: + details: + minLength: 1 + type: string + field: + type: string + ref: + format: uri + nullable: true + type: string + required: + - details + title: Push field validation + type: object + pushOptionChoice: + properties: + description: + type: string + displayName: + type: string + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + value: + description: Allowed value for field. + minLength: 1 + type: string + title: Push Option Choice + type: object + pushOptionProperty: + properties: + description: + minLength: 1 + type: string + displayName: + minLength: 1 + type: string + options: + items: + $ref: "#/components/schemas/PushOption/definitions/pushOptionChoice" + nullable: true + type: array + properties: + additionalProperties: + $ref: "#/components/schemas/PushOption/definitions/pushOptionProperty" + nullable: true + type: object + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + validation: + $ref: "#/components/schemas/PushOption/definitions/pushValidationInfo" + required: + - description + - displayName + - required + - type + title: Push Option Property + type: object + pushOptionType: + enum: + - Array + - Object + - String + - Number + - Boolean + - DateTime + - File + - MultiPart + title: Option Type + type: string + pushValidationInfo: + additionalProperties: false + properties: + information: + items: + $ref: "#/components/schemas/PushOption/definitions/pushFieldValidation" + nullable: true + type: array + warnings: + items: + $ref: "#/components/schemas/PushOption/definitions/pushFieldValidation" + nullable: true + type: array + title: Push validation info + type: object + properties: + description: + type: string + displayName: + minLength: 1 + type: string + options: + items: + $ref: "#/components/schemas/PushOption/definitions/pushOptionChoice" + type: + - array + - "null" + properties: + additionalProperties: + $ref: "#/components/schemas/PushOption/definitions/pushOptionProperty" + type: + - object + - "null" + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + validation: + $ref: "#/components/schemas/PushOption/definitions/pushValidationInfo" + nullable: true + required: + - displayName + - required + - type + title: Push Option + type: object + x-internal: true + ReportLine: + properties: + accountId: + description: Identifier for the account, unique for the company in the accounting platform. + type: + - string + - "null" + items: + description: An array of ReportLine items. + items: + $ref: "#/components/schemas/ReportLine" + type: + - array + - "null" + name: + description: Name of the report line item. + type: + - string + - "null" + value: + description: Numerical value of the line item. + type: number + required: + - value + title: Report Line + type: object + x-internal: true + SalesOrder: + allOf: + - properties: + currency: + $ref: "#/components/schemas/Transfer/definitions/transferAccount/properties/currency" + description: Currency of the sales order. + currencyRate: + $ref: "#/components/schemas/BillPayment/definitions/billPaymentLineLink/properties/currencyRate" + customerPurchaseOrderNumber: + description: A customer-supplied identifier for the purchase order in the customer's system. + type: + - string + - "null" + customerRef: + $ref: "#/components/schemas/Customer/definitions/customerRef" + description: The customer that the sales order is recorded against in the accounting system. + expectedDeliveryDate: + $ref: "#/components/schemas/DateTime" + description: Expected delivery date for any goods that have been ordered. + nullable: true + id: + description: Identifier for the sales order, unique for the company in the accounting platform. + type: string + invoicingStatus: + $ref: "#/components/schemas/SalesOrder/definitions/salesOrderInvoiceStatus" + issueDate: + $ref: "#/components/schemas/DateTime" + description: Date of the sales order as recorded in the accounting platform. + lineItems: + description: An array of line items. + items: + $ref: "#/components/schemas/SalesOrder/definitions/salesOrderLineItem" + type: + - array + - "null" + metadata: + $ref: "#/components/schemas/Metadata" + note: + description: Any additional information associated with the sales order. + type: + - string + - "null" + salesOrderNumber: + description: Friendly reference for the sales order, commonly generated by the accounting platform. + type: + - string + - "null" + shipTo: + description: Delivery details for any goods that have been ordered. + properties: + address: + $ref: "#/components/schemas/CompanyDataset/properties/addresses/items" + description: Delivery address for any goods that have been ordered. + contact: + description: Details of the named contact at the delivery address. + properties: + email: + description: Email address of the contact at the delivery address. + type: + - string + - "null" + name: + description: Name of the contact at the delivery address. + type: + - string + - "null" + phone: + description: Phone number of the contact at the delivery address. + type: + - string + - "null" + type: object + title: Ship to + type: object + status: + $ref: "#/components/schemas/SalesOrder/definitions/salesOrderStatus" + subTotal: + description: Total amount of the sales order, including discounts but excluding tax. + type: number + totalAmount: + description: Total amount of the sales order, including discounts and tax. + type: number + totalDiscount: + description: |- + + Total value of any discounts applied to the sales order. + type: number + totalTaxAmount: + description: Total amount of tax included in the sales order. + type: number + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + salesOrderInvoiceStatus: + description: If the sales order is converted to an invoice, or will be in future, the invoicingStatus field indicates the current stage of the invoicing process. + enum: + - Unknown + - PartiallyInvoiced + - Invoiced + - NotInvoiced + type: string + salesOrderLineItem: + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: Reference to the account to which the line item is linked. + description: + description: Description of the goods or services that have been ordered. + nullable: true + type: string + discountAmount: + description: Value of any discounts applied. + type: number + discountPercentage: + description: Percentage rate (from 0 to 100) of any discounts applied to the unit amount. + type: number + itemRef: + $ref: "#/components/schemas/Item/definitions/itemRef" + description: Reference to the product or inventory item to which the line item is linked. + quantity: + description: Number of units that have been ordered. + type: number + subTotal: + description: Amount of the line, inclusive of discounts but exclusive of tax. + type: number + taxAmount: + description: Amount of tax for the line. + type: number + taxRateRef: + $ref: "#/components/schemas/TaxRate/definitions/taxRateRef" + description: Reference to the tax rate to which the line item is linked. + totalAmount: + description: Total amount of the line, inclusive of discounts and tax. + type: number + tracking: + properties: + recordRefs: + items: + $ref: "#/components/schemas/DirectCost/definitions/tracking/properties/invoiceTo" + nullable: true + type: array + type: object + unitAmount: + description: Price of each unit. + type: number + title: Invoice line item + type: object + salesOrderStatus: + description: Current state of the sales order. + enum: + - Unknown + - Draft + - Open + - Closed + - Void + type: string + description: |- + > View the coverage for sales orders in the Data coverage explorer. + + ## Overview + + A sales order represents a customer's intention to purchase goods or services from a seller and usually includes information such as the expected delivery date and shipping details. This information can be used to provide visibility on a business's expected receivables and to track sales through the full procurement process. + + A sales order is typically converted to an [invoice](https://docs.codat.io/accounting-api#/schemas/Invoice) after approval. + examples: + - currency: GBP + currencyRate: 0 + customerPurchaseOrderNumber: string + customerRef: + companyName: string + id: string + expectedDeliveryDate: 2022-10-23T00:00:00Z + id: string + invoicingStatus: Unknown + issueDate: 2022-10-23T00:00:00Z + lineItems: + - accountRef: + id: string + name: string + description: string + discountAmount: 0 + discountPercentage: 0 + itemRef: + id: string + name: string + quantity: 0 + subTotal: 0 + taxAmount: 0 + taxRateRef: + effectiveTaxRate: 0 + id: string + name: string + totalAmount: 0 + tracking: + recordRefs: + - string + unitAmount: 0 + metadata: + isDeleted: true + modifiedDate: 2022-10-23T00:00:00Z + note: string + salesOrderNumber: string + shipTo: + address: + city: string + country: string + line1: string + line2: string + postalCode: string + region: string + type: Unknown + contact: + email: string + name: string + phone: string + sourceModifiedDate: 2022-10-23T00:00:00Z + status: Unknown + subTotal: 0 + totalAmount: 0 + totalDiscount: 0 + totalTaxAmount: 0 + title: Sales order + type: object + SalesOrders: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/SalesOrder" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + Supplier: + allOf: + - properties: + addresses: + description: An array of Addresses. + items: + $ref: "#/components/schemas/CompanyDataset/properties/addresses/items" + type: + - array + - "null" + contactName: + description: Name of the main contact for the supplier. + type: + - string + - "null" + defaultCurrency: + description: Default currency the supplier's transactional data is recorded in. + type: + - string + - "null" + emailAddress: + description: Email address that the supplier may be contacted on. + type: + - string + - "null" + id: + description: Identifier for the supplier, unique to the company in the accounting platform. + type: string + metadata: + $ref: "#/components/schemas/Metadata" + phone: + description: Phone number that the supplier may be contacted on. + examples: + - +44 25691 154789 + - (877) 492-8687 + - 01224 658 999 + type: + - string + - "null" + registrationNumber: + description: Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. + type: + - string + - "null" + status: + $ref: "#/components/schemas/Supplier/definitions/supplierStatus" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + supplierName: + description: Name of the supplier as recorded in the accounting system, typically the company name. + type: + - string + - "null" + taxNumber: + description: Supplier's company tax number. + type: + - string + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + supplierRef: + description: Reference to the supplier the record relates to. + properties: + id: + description: The supplier's unique ID + minLength: 1 + type: string + supplierName: + description: The supplier's name + nullable: true + type: string + required: + - id + title: Supplier reference + type: object + supplierStatus: + description: Status of the supplier. + enum: + - Unknown + - Active + - Archived + type: string + description: |- + > View the coverage for suppliers in the Data coverage explorer. + + ## Overview + + From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/accounting-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/accounting-api#/schemas/Bill). + examples: + - addresses: + - city: Bakersfield + country: USA + line1: Unit 51 + line2: Bakersfield Industrial Estate + postalcode: "93308" + region: California + type: Billing + contactName: Kelly's Industrial Supplies + defaultCurrency: string + emailAddress: sales@kellysupplies.com + id: C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F + metadata: + isDeleted: true + modifiedDate: 2022-10-23T00:00:00Z + phone: 07999 999999 + registrationNumber: string + sourceModifiedDate: 2022-10-23T00:00:00Z + status: Unknown + supplementalData: + content: + property1: + property1: null + property2: null + property2: + property1: null + property2: null + supplierName: Kelly's Industrial Supplies + taxNumber: string + required: + - status + title: Supplier + type: object + Suppliers: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Supplier" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + TaxRate: + allOf: + - properties: + code: + description: Code for the tax rate from the accounting platform. + type: + - string + - "null" + components: + items: + $ref: "#/components/schemas/TaxRate/definitions/taxRateComponent" + type: + - array + - "null" + effectiveTaxRate: + description: See Effective tax rates description. + type: + - number + - "null" + id: + description: Identifier for the tax rate, unique for the company in the accounting platform. + type: string + metadata: + $ref: "#/components/schemas/Metadata" + name: + description: Codat-augmented name of the tax rate in the accounting platform. + type: + - string + - "null" + status: + $ref: "#/components/schemas/TaxRate/definitions/taxRateStatus" + totalTaxRate: + description: Total (not compounded) sum of the components of a tax rate. + type: + - number + - "null" + validDatatypeLinks: + items: + $ref: "#/components/schemas/ValidDataTypeLinks" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + taxRateComponent: + additionalProperties: false + description: A tax rate can be made up of multiple sub taxes, often called components of the tax. + properties: + isCompound: + description: "A flag to indicate with the tax is calculated using the principle of compounding. " + type: boolean + name: + description: Name of the tax rate component. + nullable: true + type: string + rate: + description: The rate of the tax rate component, usually a percentage. + nullable: true + type: number + required: + - isCompound + title: Tax Rate Component + type: object + taxRateRef: + description: |- + Data types that reference a tax rate, for example invoice and bill line items, use a taxRateRef that includes the ID and name of the linked tax rate. + + Found on: + + - Bill line items + - Bill Credit Note line items + - Credit Note line items + - Direct incomes line items + - Invoice line items + - Items + properties: + effectiveTaxRate: + description: Applicable tax rate. + type: number + id: + description: Unique identifier for the tax rate in the accounting platform. + type: string + name: + description: Name of the tax rate in the accounting platform. + type: string + title: Tax rate reference + type: object + taxRateStatus: + description: |- + Status of the tax rate in the accounting platform. + - `Active` - An active tax rate in use by a company. + - `Archived` - A tax rate that has been archived or is inactive in the accounting platform. + - `Unknown` - Where the status of the tax rate cannot be determined from the underlying platform. + enum: + - Unknown + - Active + - Archived + title: Tax rate status + type: string + description: |- + > View the coverage for tax rates in the Data coverage explorer. + + ## Overview + + Accounting systems typically store a set of taxes and associated rates within the accounting package. This means that users don't have to look up or remember the rates for each type of tax. For example, applying the tax "UK sales VAT" to line items of an invoice adds the correct rate of 20%. + + ### Tax components + + In some cases, a tax is made up of multiple sub taxes, often called _components_ of the tax. For example, you may have an item that is charged a tax rate called "City import tax (8%)" that has two components: + + - A city tax of 5% + - An import tax of 3% + + > **Effective tax rates** + > - Where there are multiple components of a tax, each component may be calculated on the original amount and added together. Alternatively, one tax may be calculated on the sub-total of the original amount plus another tax, which is referred to as _compounding_. When there is compounding, the effective tax rate is the rate that, if applied to the original amount, would result in the total amount of tax with compounding. + > + > **Example:** + > A tax has two components. Both components have a rate of 10%, and one component is compound. In this case, there is a total tax rate of 20% but an effective tax rate of 21%. + > + > - For QuickBooks Online, Codat doesn't use compound rates. Instead, the calculated effective tax rate for each component is shown. This means that the effective and total rates are the same because the total tax rate is a sum of the component rates. + title: Tax Rate + type: object + TaxRates: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/TaxRate" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + TrackingCategories: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/TrackingCategory" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + TrackingCategory: + allOf: + - properties: + hasChildren: + description: Boolean value indicating whether this category has SubCategories + type: boolean + id: + description: The identifier for the item, unique per tracking category + type: + - string + - "null" + name: + description: The name of the tracking category + type: + - string + - "null" + parentId: + description: The identifier for this item's immediate parent + type: + - string + - "null" + status: + $ref: "#/components/schemas/TrackingCategory/definitions/status" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + status: + description: Current state of the tracking category. + enum: + - Unknown + - Active + - Archived + title: Tracking category status + type: string + trackingCategoryRef: + deprecated: true + description: References a category against which the item is tracked. + properties: + id: + minLength: 1 + type: string + name: + nullable: true + type: string + required: + - id + type: object + description: |- + Details of a category used for tracking transactions. + + > Language tip + > + > Parameters used to track types of spend in various parts of an organization can be called **dimensions**, **projects**, **classes**, or **locations** in different accounting platforms. In Codat, we refer to these as tracking categories. + + View the coverage for tracking categories in the Data coverage explorer. + + ## Overview + + Tracking categories are used to monitor cost centres and control budgets that sit outside the standard chart of accounts. Customers may use tracking categories to group together and track the income and costs of specific departments, projects, locations or customers. + + From their accounting system, customers can: + + - Create and maintain tracking categories and tracking category types. + - View all tracking categories that are available for use. + - View the relationships between the categories. + - Assign invoices, bills, credit notes, or bill credit notes to one or more categories. + - View the categories that a transaction belongs to. + - View all transactions in a tracking category. + + > **Example use case** + > + > Monitor the budget for your annual conference using a tracking category called 'AnnualConference2020' with the **type** set to **Costing**. + + If a tracking category has a parent category, the ID of that parent category is displayed. There is also a `hasChildren` field that shows whether there are child subcategories nested beneath. + examples: + - hasChildren: true + id: string + modifiedDate: 2022-10-23T00:00:00Z + name: string + parentId: string + sourceModifiedDate: 2022-10-23T00:00:00Z + status: Unknown + title: Tracking category + type: object + TrackingCategoryTree: + allOf: + - properties: + hasChildren: + description: Boolean value indicating whether this category has SubCategories + type: boolean + id: + description: The identifier for the item, unique per tracking category + type: + - string + - "null" + name: + description: The name of the tracking category + type: + - string + - "null" + parentId: + description: The identifier for this item's immediate parent + type: + - string + - "null" + status: + $ref: "#/components/schemas/TrackingCategory/definitions/status" + subCategories: + description: A collection of subcategories that are nested beneath this category. + items: + $ref: "#/components/schemas/TrackingCategoryTree" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + description: The full structure of a specific tracking category including any child or subcategories. + title: Tracking category tree + type: object + Transfer: + allOf: + - properties: + contactRef: + description: The customer or supplier for the transfer, if available. + properties: + dataType: + type: + - string + - "null" + id: + minLength: 1 + type: string + required: + - id + type: object + date: + $ref: "#/components/schemas/DateTime" + description: The day on which the transfer was made. + depositedRecordRefs: + items: + type: string + type: + - array + - "null" + description: + description: Description of the transfer. + type: + - string + - "null" + from: + $ref: "#/components/schemas/Transfer/definitions/transferAccount" + description: The details of the accounts the transfer is moving from. + id: + description: Unique identifier for the transfer. + type: string + metadata: + $ref: "#/components/schemas/Metadata" + supplementalData: + $ref: "#/components/schemas/Bill/allOf/0/properties/supplementalData" + to: + $ref: "#/components/schemas/Transfer/definitions/transferAccount" + description: The details of the accounts the transfer is moving to. + trackingCategoryRefs: + description: Reference to the tracking categories this transfer is being tracked against. + items: + $ref: "#/components/schemas/TrackingCategory/definitions/trackingCategoryRef" + type: + - array + - "null" + type: object + - $ref: "#/components/schemas/ModifiedDates" + definitions: + transferAccount: + description: "" + properties: + accountRef: + $ref: "#/components/schemas/Account/definitions/accountRef" + description: The account that the transfer is moving from or to. + amount: + description: The amount transferred between accounts. + type: number + currency: + description: |- + The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + + ## Unknown currencies + + In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. + + There are only a very small number of edge cases where this currency code is returned by the Codat system. + examples: + - GBP + - USD + - EUR + format: ISO4217 + title: Currency + type: string + x-internal: true + title: Transfer account + type: object + description: |- + > View the coverage for transfers in the Data coverage explorer. + + A transfer records the movement of money between two bank accounts, or between a bank account and a nominal account. It is a child data type of [account transactions](https://docs.codat.io/accounting-api#/schemas/AccountTransaction). + title: Transfer + type: object + Transfers: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/Transfer" + type: array + type: object + - $ref: "#/components/schemas/PagingInfo" + x-internal: true + UpdateBankAccountResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BankAccount" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdateBillCreditNoteResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BillCreditNote" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdateBillResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Bill" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdateCreditNoteResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/CreditNote" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdateCustomerResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Customer" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdateInvoiceResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/Invoice" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + UpdatePurchaseOrderResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/PurchaseOrder" + type: object + - $ref: "#/components/schemas/PushOperationSummary" + x-internal: true + ValidDataTypeLinks: + description: |- + When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. + + For example, `validDatatypeLinks` might indicate the following references: + + - Which tax rates are valid to use on the line item of a bill. + - Which items can be used when creating an invoice. + + You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. + + ## `validDatatypeLinks` example + + The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. + + ```json validDatatypeLinks for an account + { + "id": "bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4", + "nominalCode": "090", + "name": "Business Bank Account", + #... + "validDatatypeLinks": [ + { + "property": "Id", + "links": [ + "Payment.AccountRef.Id", + "BillPayment.AccountRef.Id", + "DirectIncome.LineItems.AccountRef.Id", + "DirectCost.LineItems.AccountRef.Id" + ] + } + ] + } + ``` + + + + ## Support for `validDatatypeLinks` + + Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. + + If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. + properties: + links: + description: Supported `dataTypes` that the record can be linked to. + items: + type: string + type: + - array + - "null" + property: + description: The property from the account that can be linked. + type: + - string + - "null" + title: Valid data type links + type: object + securitySchemes: + auth_header: + description: The word "Basic" followed by a space and your API Key, base64 encoded, which can be found [here](https://app.codat.io/developers/api-keys) + in: header + name: Authorization + type: apiKey +x-speakeasy-retries: + backoff: + exponent: 1.5 + initialInterval: 500 + maxElapsedTime: 3600000 + maxInterval: 60000 + retryConnectionErrors: true + statusCodes: + - 408 + - 429 + - 5XX + strategy: backoff +x-stoplight: + id: tfrhp9p2h6on2 diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_bank_feeds.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_bank_feeds.yaml new file mode 100644 index 000000000..a654d20af --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/codat_bank_feeds.yaml @@ -0,0 +1,833 @@ +openapi: 3.1.0 +servers: + - description: Production + url: https://api.codat.io +info: + contact: + email: support@codat.io + name: Codat + description: |- + Bank Feeds API enables your SMB users to set up bank feeds from accounts in your application to supported accounting platforms. + + A bank feed is a connection between a source bank account—in your application—and a target bank account in a supported accounting package. + + [Read more...](https://docs.codat.io/bank-feeds-api/overview) + + [See our OpenAPI spec](https://github.com/codatio/oas) + termsOfService: https://www.codat.io/legals/ + title: Bank Feeds API + version: 2.1.0 + x-apisguru-categories: + - financial + x-logo: + url: https://static.codat.io/public/branding/codat-icon-blue.svg + x-origin: + - format: openapi + url: https://raw.githubusercontent.com/codatio/oas/main/json/Codat-Bank-Feeds.json + version: "3.1" + x-providerName: codat.io + x-serviceName: bank-feeds +security: + - auth_header: [] +tags: + - description: Bank feed bank accounts + name: Bank feed accounts + - description: Bank feed bank accounts + name: Bank account transactions +paths: + "/companies/{companyId}/connections/{connectionId}/connectionInfo/bankFeedAccounts": + get: + description: Get BankFeed BankAccounts for a single data source connected to a single company. + operationId: get-bank-feeds + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankFeedAccounts" + description: Success + summary: List bank feed bank accounts + tags: + - Bank feed accounts + put: + description: Put BankFeed BankAccounts for a single data source connected to a single company. + operationId: create-bank-feed + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankFeedAccounts" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankFeedAccounts" + description: Success + summary: Create bank feed bank accounts + tags: + - Bank feed accounts + "/companies/{companyId}/connections/{connectionId}/connectionInfo/bankFeedAccounts/{accountId}": + patch: + description: Update a single BankFeed BankAccount for a single data source connected to a single company. + operationId: update-bank-feed + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/accountId" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankFeedAccount" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankFeedAccount" + x-speakeasy-usage-example: true + description: Success + summary: Update bank feed bank account + tags: + - Bank feed accounts + "/companies/{companyId}/connections/{connectionId}/data/bankAccounts/{accountId}/bankTransactions": + get: + description: Gets bank transactions for a given bank account ID + operationId: list-bank-account-transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/accountId" + - $ref: "#/components/parameters/page" + - $ref: "#/components/parameters/pageSize" + - $ref: "#/components/parameters/query" + - $ref: "#/components/parameters/orderBy" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BankTransactionsResponse" + description: Success + summary: List bank transactions for bank account + tags: + - Bank account transactions + "/companies/{companyId}/connections/{connectionId}/options/bankAccounts/{accountId}/bankTransactions": + get: + description: Gets the options of pushing bank account transactions. + operationId: get-create-bank-account-model + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/accountId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PushOption" + description: Success + summary: List push options for bank account bank transactions + tags: + - Bank account transactions + x-extension-1: null + "/companies/{companyId}/connections/{connectionId}/push/bankAccounts/{accountId}/bankTransactions": + post: + description: |- + Posts bank transactions to the accounting package for a given company. + + > **Supported Integrations** + > + > Check out our [Knowledge UI](https://knowledge.codat.io/supported-features/accounting?view=tab-by-data-type&dataType=bankTransactions) for integrations that support POST methods. + operationId: create-bank-transactions + parameters: + - $ref: "#/components/parameters/companyId" + - $ref: "#/components/parameters/connectionId" + - $ref: "#/components/parameters/accountId" + - in: query + name: allowSyncOnPushComplete + schema: + default: true + type: boolean + x-stoplight: + id: kc8ehjqr6p02q + - in: query + name: timeoutInMinutes + schema: + format: int32 + type: integer + x-stoplight: + id: irz50qjbs3yef + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BankTransactions" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CreateBankTransactionsResponse" + description: Success + summary: Create bank transactions + tags: + - Bank account transactions +components: + parameters: + accountId: + description: Unique identifier for an account + in: path + name: accountId + required: true + schema: + example: 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + companyId: + in: path + name: companyId + required: true + schema: + description: Unique identifier for your SMB in Codat. + example: 8a210b68-6988-11ed-a1eb-0242ac120002 + format: uuid + type: string + connectionId: + in: path + name: connectionId + required: true + schema: + description: Unique identifier for a company's data connection. + example: 2e9d2c44-f675-40ba-8049-353bfcb5e171 + format: uuid + type: string + orderBy: + description: Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). + in: query + name: orderBy + required: false + schema: + example: -modifiedDate + type: string + x-stoplight: + id: 4je9lwo02netu + page: + description: Page number. [Read more](https://docs.codat.io/using-the-api/paging). + in: query + name: page + required: true + schema: + default: 1 + example: 1 + format: int32 + minimum: 0 + type: integer + x-stoplight: + id: 1318joqblpp4e + pageSize: + description: Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). + in: query + name: pageSize + schema: + default: 100 + example: 100 + format: int32 + maximum: 5000 + minimum: 1 + type: integer + x-stoplight: + id: s2ika6rltk5y6 + query: + description: Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). + in: query + name: query + required: false + schema: + type: string + x-stoplight: + id: gupdb9kt30hfq + schemas: + BankFeedAccount: + additionalProperties: false + description: The target bank account in a supported accounting package for ingestion into a bank feed. + examples: + - accountName: account-081 + accountNumber: "12345670" + accountType: Credit + balance: 99.99 + currency: GBP + id: acc-002 + modifiedDate: 2023-01-09T14:14:14.1057478Z + sortCode: "123456" + status: pending + - accountName: account-095 + accountNumber: "12345671" + accountType: Credit + balance: 0 + currency: USD + id: acc-003 + modifiedDate: 2023-01-09T14:14:14.1057478Z + sortCode: "123456" + status: pending + properties: + accountName: + description: The bank account name + nullable: true + type: string + accountNumber: + description: The account number + nullable: true + type: string + accountType: + description: The type of bank account e.g. Credit + nullable: true + type: string + balance: + description: The latest balance for the bank account + nullable: true + type: number + currency: + description: The currency e.g. USD + nullable: true + type: string + feedStartDate: + $ref: "#/components/schemas/DateTime" + nullable: true + id: + description: Unique ID for the bank feed account + type: string + modifiedDate: + $ref: "#/components/schemas/DateTime" + description: The last date the bank account was modified + nullable: true + sortCode: + description: The sort code + nullable: true + type: string + status: + nullable: true + type: string + required: + - id + title: Bank Feed Account + type: object + BankFeedAccounts: + items: + $ref: "#/components/schemas/BankFeedAccount" + type: array + x-internal: true + BankTransactions: + definitions: + bankTransactionLine: + allOf: + - properties: + amount: + type: number + balance: + type: number + clearedOnDate: + $ref: "#/components/schemas/DateTime" + counterparty: + nullable: true + type: string + description: + nullable: true + type: string + id: + type: string + reconciled: + type: boolean + reference: + nullable: true + type: string + transactionType: + $ref: "#/components/schemas/BankTransactions/definitions/bankTransactionType" + type: object + - allOf: + - properties: + modifiedDate: + $ref: "#/components/schemas/DateTime" + description: The date on which this record was last modified in Codat. + title: ModifiedDate + type: object + x-internal: true + - properties: + sourceModifiedDate: + $ref: "#/components/schemas/DateTime" + description: The date on which this record was last modified in the originating system + title: Source Modified Date + type: object + x-internal: true + x-internal: true + required: + - amount + - balance + - date + - reconciled + - transactionType + title: Bank transaction line + type: object + bankTransactionType: + description: Type of transaction for the bank statement line + enum: + - Unknown + - Credit + - Debit + - Int + - Div + - Fee + - SerChg + - Dep + - Atm + - Pos + - Xfer + - Check + - Payment + - Cash + - DirectDep + - DirectDebit + - RepeatPmt + - Other + title: Bank transaction type + type: string + description: |- + > **Accessing Bank Accounts through Banking API** + > + > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. + > + > To view bank account data through the Banking API, please refer to the new datatype [here](https://docs.codat.io/banking-api#/operations/list-all-banking-transactions) + + > View the coverage for bank transactions in the Data coverage explorer. + + ## Overview + + Transactional banking data for a specific company and account. + + Bank transactions include the: + * Amount of the transaction. + * Current account balance. + * Transaction type, for example, credit, debit, or transfer. + properties: + accountId: + nullable: true + type: string + transactions: + items: + $ref: "#/components/schemas/BankTransactions/definitions/bankTransactionLine" + nullable: true + type: array + title: Bank account transactions + type: object + BankTransactionsResponse: + allOf: + - properties: + results: + items: + $ref: "#/components/schemas/BankTransactions" + type: array + type: object + - examples: + - _links: + current: + href: /companies/{id}/data/{dataType}?page=1&pageSize=10 + pageNumber: 1 + pageSize: 10 + self: + href: /companies/{id}/data/{dataType} + totalResults: 1 + properties: + _links: + $ref: "#/components/schemas/Links" + pageNumber: + type: integer + pageSize: + type: integer + totalResults: + type: integer + required: + - pageNumber + - pageSize + - totalResults + - _links + type: object + x-internal: true + x-internal: true + CreateBankTransactionsResponse: + allOf: + - properties: + data: + $ref: "#/components/schemas/BankTransactions" + type: object + - $ref: "#/components/schemas/PushOperation" + x-internal: true + DataType: + description: Available Data types + enum: + - accountTransactions + - balanceSheet + - bankAccounts + - bankTransactions + - billCreditNotes + - billPayments + - bills + - cashFlowStatement + - chartOfAccounts + - company + - creditNotes + - customers + - directCosts + - directIncomes + - invoices + - items + - journalEntries + - journals + - paymentMethods + - payments + - profitAndLoss + - purchaseOrders + - salesOrders + - suppliers + - taxRates + - trackingCategories + - transfers + - banking-accountBalances + - banking-accounts + - banking-transactionCategories + - banking-transactions + - commerce-companyInfo + - commerce-customers + - commerce-disputes + - commerce-locations + - commerce-orders + - commerce-paymentMethods + - commerce-payments + - commerce-productCategories + - commerce-products + - commerce-taxComponents + - commerce-transactions + example: invoices + type: string + x-internal: true + DateTime: + description: |- + In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + + ``` + 2020-10-08T22:40:50Z + 2021-01-01T00:00:00 + ``` + + + + When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + + - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` + - Unqualified local time: `2021-11-15T01:00:00` + - UTC time offsets: `2021-11-15T01:00:00-05:00` + + > Time zones + > + > Not all dates from Codat will contain information about time zones. + > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + example: 2022-10-23T00:00:00Z + title: Date time + type: string + HRef: + properties: + href: + format: uri-reference + type: string + title: Hypertext reference + type: object + x-internal: true + Links: + examples: + - current: + href: /companies/{id}/data/{dataType}?page=1&pageSize=10 + self: + href: /companies/{id}/data/{dataType} + properties: + current: + $ref: "#/components/schemas/HRef" + next: + $ref: "#/components/schemas/HRef" + previous: + $ref: "#/components/schemas/HRef" + self: + $ref: "#/components/schemas/HRef" + required: + - self + - current + type: object + x-internal: true + PushOperation: + definitions: + pushChangeType: + enum: + - Unknown + - Created + - Modified + - Deleted + - AttachmentUploaded + title: Push change type + type: string + pushOperationChange: + properties: + attachmentId: + nullable: true + type: string + recordRef: + $ref: "#/components/schemas/PushOperation/definitions/pushOperationRef" + type: + $ref: "#/components/schemas/PushOperation/definitions/pushChangeType" + type: object + pushOperationRef: + additionalProperties: false + properties: + dataType: + $ref: "#/components/schemas/DataType" + nullable: true + id: + type: string + title: Push operation reference + type: object + x-internal: true + pushOperationStatus: + description: The status of the push operation. + enum: + - Pending + - Failed + - Success + - TimedOut + title: Push operation status + type: string + validation: + description: A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + properties: + errors: + items: + $ref: "#/components/schemas/PushOperation/definitions/validationItem" + nullable: true + type: array + warnings: + items: + $ref: "#/components/schemas/PushOperation/definitions/validationItem" + nullable: true + type: array + title: Validation + type: object + validationItem: + additionalProperties: false + properties: + itemId: + nullable: true + type: string + message: + nullable: true + type: string + validatorName: + nullable: true + type: string + title: Validation item + type: object + properties: + changes: + items: + $ref: "#/components/schemas/PushOperation/definitions/pushOperationChange" + nullable: true + type: array + companyId: + $ref: "#/components/parameters/companyId/schema" + completedOnUtc: + $ref: "#/components/schemas/DateTime" + description: The datetime when the push was completed, null if Pending. + dataConnectionKey: + $ref: "#/components/parameters/connectionId/schema" + dataType: + $ref: "#/components/schemas/DataType" + description: The type of data being pushed, eg invoices, customers. + nullable: true + errorMessage: + nullable: true + type: string + pushOperationKey: + description: A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted. + format: uuid + type: string + requestedOnUtc: + $ref: "#/components/schemas/DateTime" + description: The datetime when the push was requested. + status: + $ref: "#/components/schemas/PushOperation/definitions/pushOperationStatus" + statusCode: + type: integer + timeoutInMinutes: + format: int32 + nullable: true + type: integer + timeoutInSeconds: + deprecated: true + format: int32 + nullable: true + type: integer + validation: + $ref: "#/components/schemas/PushOperation/definitions/validation" + required: + - companyId + - pushOperationKey + - dataConnectionKey + - requestedOnUtc + - status + - statusCode + type: object + x-internal: true + PushOption: + definitions: + pushFieldValidation: + additionalProperties: false + properties: + details: + minLength: 1 + type: string + field: + type: string + ref: + format: uri + nullable: true + type: string + required: + - details + title: Push field validation + type: object + pushOptionChoice: + properties: + description: + type: string + displayName: + type: string + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + value: + description: Allowed value for field. + minLength: 1 + type: string + title: Push Option Choice + type: object + pushOptionProperty: + properties: + description: + minLength: 1 + type: string + displayName: + minLength: 1 + type: string + options: + items: + $ref: "#/components/schemas/PushOption/definitions/pushOptionChoice" + nullable: true + type: array + properties: + additionalProperties: + $ref: "#/components/schemas/PushOption/definitions/pushOptionProperty" + nullable: true + type: object + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + validation: + $ref: "#/components/schemas/PushOption/definitions/pushValidationInfo" + required: + - description + - displayName + - required + - type + title: Push Option Property + type: object + pushOptionType: + enum: + - Array + - Object + - String + - Number + - Boolean + - DateTime + - File + - MultiPart + title: Option Type + type: string + pushValidationInfo: + additionalProperties: false + properties: + information: + items: + $ref: "#/components/schemas/PushOption/definitions/pushFieldValidation" + nullable: true + type: array + warnings: + items: + $ref: "#/components/schemas/PushOption/definitions/pushFieldValidation" + nullable: true + type: array + title: Push validation info + type: object + properties: + description: + type: string + displayName: + minLength: 1 + type: string + options: + items: + $ref: "#/components/schemas/PushOption/definitions/pushOptionChoice" + nullable: true + type: array + properties: + additionalProperties: + $ref: "#/components/schemas/PushOption/definitions/pushOptionProperty" + nullable: true + type: object + required: + type: boolean + type: + $ref: "#/components/schemas/PushOption/definitions/pushOptionType" + validation: + $ref: "#/components/schemas/PushOption/definitions/pushValidationInfo" + nullable: true + required: + - displayName + - required + - type + title: Push Option + type: object + x-internal: true + securitySchemes: + auth_header: + description: The word "Basic" followed by a space and your API Key, base64 encoded, which can be found [here](https://app.codat.io/developers/api-keys) + in: header + name: Authorization + type: apiKey +x-speakeasy-retries: + backoff: + exponent: 1.5 + initialInterval: 500 + maxElapsedTime: 3600000 + maxInterval: 60000 + retryConnectionErrors: true + statusCodes: + - 408 + - 429 + - 5XX + strategy: backoff +x-stoplight: + id: j388fn92qyj2u diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/disclosure.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/disclosure.yaml new file mode 100644 index 000000000..d7ec8481e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/disclosure.yaml @@ -0,0 +1,11531 @@ +openapi: 3.1.0 +servers: + - url: http://discourse.local + - url: https://{defaultHost} + variables: + defaultHost: + default: discourse.example.com +info: + description: | + This page contains the documentation on how to use Discourse through API calls. + + > Note: For any endpoints not listed you can follow the + [reverse engineer the Discourse API](https://meta.discourse.org/t/-/20576) + guide to figure out how to use an API endpoint. + + ### Request Content-Type + + The Content-Type for POST and PUT requests can be set to `application/x-www-form-urlencoded`, + `multipart/form-data`, or `application/json`. + + ### Endpoint Names and Response Content-Type + + Most API endpoints provide the same content as their HTML counterparts. For example + the URL `/categories` serves a list of categories, the `/categories.json` API provides the + same information in JSON format. + + Instead of sending API requests to `/categories.json` you may also send them to `/categories` + and add an `Accept: application/json` header to the request to get the JSON response. + Sending requests with the `Accept` header is necessary if you want to use URLs + for related endpoints returned by the API, such as pagination URLs. + These URLs are returned without the `.json` prefix so you need to add the header in + order to get the correct response format. + + ### Authentication + + Some endpoints do not require any authentication, pretty much anything else will + require you to be authenticated. + + To become authenticated you will need to create an API Key from the admin panel. + + Once you have your API Key you can pass it in along with your API Username + as an HTTP header like this: + + ``` + curl -X GET "http://127.0.0.1:3000/admin/users/list/active.json" \ + -H "Api-Key: 714552c6148e1617aeab526d0606184b94a80ec048fc09894ff1a72b740c5f19" \ + -H "Api-Username: system" + ``` + + and this is how POST requests will look: + + ``` + curl -X POST "http://127.0.0.1:3000/categories" \ + -H "Content-Type: multipart/form-data;" \ + -H "Api-Key: 714552c6148e1617aeab526d0606184b94a80ec048fc09894ff1a72b740c5f19" \ + -H "Api-Username: system" \ + -F "name=89853c20-4409-e91a-a8ea-f6cdff96aaaa" \ + -F "color=49d9e9" \ + -F "text_color=f0fcfd" + ``` + + ### Boolean values + + If an endpoint accepts a boolean be sure to specify it as a lowercase + `true` or `false` value unless noted otherwise. + license: + name: MIT + url: https://docs.discourse.org/LICENSE.txt + title: Discourse API Documentation + version: latest + x-apisguru-categories: + - social + x-logo: + url: https://docs.discourse.org/logo.svg + x-origin: + - format: openapi + url: http://docs.discourse.org/openapi.json + version: "3.1" + x-providerName: discourse.local +paths: + /admin/backups.json: + get: + operationId: getBackups + responses: + "200": + content: + application/json: + schema: + items: + properties: + filename: + type: string + last_modified: + type: string + size: + type: integer + required: + - filename + - size + - last_modified + type: object + minItems: 1 + type: array + uniqueItems: true + description: success response + summary: List backups + tags: + - Backups + post: + operationId: createBackup + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + with_uploads: + type: boolean + required: + - with_uploads + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + examples: + - OK + type: string + required: + - success + description: success response + summary: Create backup + tags: + - Backups +# "/admin/backups/{filename}": +# get: +# operationId: downloadBackup +# parameters: +# - in: path +# name: filename +# required: true +# schema: +# type: string +# - in: query +# name: token +# required: true +# schema: +# type: string +# responses: +# "200": +# description: success response +# summary: Download backup +# tags: +# - Backups +# put: +# operationId: sendDownloadBackupEmail +# parameters: +# - in: path +# name: filename +# required: true +# schema: +# type: string +# responses: +# "200": +# description: success response +# summary: Send download backup email +# tags: +# - Backups + /admin/badges.json: + get: + operationId: adminListBadges + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + admin_badges: + additionalProperties: false + properties: + badge_grouping_ids: + items: {} + type: array + badge_ids: + items: {} + type: array + badge_type_ids: + items: {} + type: array + protected_system_fields: + items: {} + type: array + triggers: + additionalProperties: false + properties: + none: + type: integer + post_action: + type: integer + post_revision: + type: integer + trust_level_change: + type: integer + user_change: + type: integer + required: + - user_change + - none + - post_revision + - trust_level_change + - post_action + type: object + required: + - protected_system_fields + - triggers + - badge_ids + - badge_grouping_ids + - badge_type_ids + type: object + badge_groupings: + items: + additionalProperties: false + properties: + description: + type: + - string + - "null" + id: + type: integer + name: + type: string + position: + type: integer + system: + type: boolean + required: + - id + - name + - description + - position + - system + type: object + type: array + badge_types: + items: + additionalProperties: false + properties: + id: + type: integer + name: + type: string + sort_order: + type: integer + required: + - id + - name + - sort_order + type: object + type: array + badges: + items: + additionalProperties: false + properties: + allow_title: + type: boolean + auto_revoke: + type: boolean + badge_grouping_id: + type: integer + badge_type_id: + type: integer + description: + type: string + enabled: + type: boolean + grant_count: + type: integer + i18n_name: + type: + - string + - "null" + icon: + type: string + id: + type: integer + image_url: + type: + - string + - "null" + listable: + type: boolean + long_description: + type: string + manually_grantable: + type: boolean + multiple_grant: + type: boolean + name: + type: string + query: + type: + - string + - "null" + show_posts: + type: boolean + slug: + type: string + system: + type: boolean + target_posts: + type: boolean + trigger: + type: + - integer + - "null" + required: + - id + - name + - description + - grant_count + - allow_title + - multiple_grant + - icon + - image_url + - listable + - enabled + - badge_grouping_id + - system + - long_description + - slug + - manually_grantable + - query + - trigger + - target_posts + - auto_revoke + - show_posts + - badge_type_id + type: object + type: array + required: + - badges + - badge_types + - badge_groupings + - admin_badges + description: success response + summary: List badges + tags: + - Badges + post: + operationId: createBadge + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + badge_type_id: + description: |- + The ID for the badge type. 1 for Gold, 2 for Silver, + 3 for Bronze. + type: integer + name: + description: The name for the new badge. + type: string + required: + - name + - badge_type_id + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + badge: + additionalProperties: false + properties: + allow_title: + type: boolean + auto_revoke: + type: boolean + badge_grouping_id: + type: integer + badge_type_id: + type: integer + description: + type: string + enabled: + type: boolean + grant_count: + type: integer + icon: + type: string + id: + type: integer + image_url: + type: + - string + - "null" + listable: + type: boolean + long_description: + type: string + manually_grantable: + type: boolean + multiple_grant: + type: boolean + name: + type: string + query: + type: + - string + - "null" + show_posts: + type: boolean + slug: + type: string + system: + type: boolean + target_posts: + type: boolean + trigger: + type: + - string + - "null" + required: + - id + - name + - description + - grant_count + - allow_title + - multiple_grant + - icon + - image_url + - listable + - enabled + - badge_grouping_id + - system + - long_description + - slug + - manually_grantable + - query + - trigger + - target_posts + - auto_revoke + - show_posts + - badge_type_id + type: object + badge_types: + items: + additionalProperties: false + properties: + id: + type: integer + name: + type: string + sort_order: + type: integer + required: + - id + - name + - sort_order + type: object + type: array + required: + - badge_types + - badge + description: success response + summary: Create badge + tags: + - Badges + "/admin/badges/{id}.json": + delete: + operationId: deleteBadge + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + description: success response + summary: Delete badge + tags: + - Badges + put: + operationId: updateBadge + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + badge_type_id: + description: |- + The ID for the badge type. 1 for Gold, 2 for Silver, + 3 for Bronze. + type: integer + name: + description: The name for the new badge. + type: string + required: + - name + - badge_type_id + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + badge: + additionalProperties: false + properties: + allow_title: + type: boolean + auto_revoke: + type: boolean + badge_grouping_id: + type: integer + badge_type_id: + type: integer + description: + type: string + enabled: + type: boolean + grant_count: + type: integer + icon: + type: string + id: + type: integer + image_url: + type: + - string + - "null" + listable: + type: boolean + long_description: + type: string + manually_grantable: + type: boolean + multiple_grant: + type: boolean + name: + type: string + query: + type: + - string + - "null" + show_posts: + type: boolean + slug: + type: string + system: + type: boolean + target_posts: + type: boolean + trigger: + type: + - string + - "null" + required: + - id + - name + - description + - grant_count + - allow_title + - multiple_grant + - icon + - image_url + - listable + - enabled + - badge_grouping_id + - system + - long_description + - slug + - manually_grantable + - query + - trigger + - target_posts + - auto_revoke + - show_posts + - badge_type_id + type: object + badge_types: + items: + additionalProperties: false + properties: + id: + type: integer + name: + type: string + sort_order: + type: integer + required: + - id + - name + - sort_order + type: object + type: array + required: + - badge_types + - badge + description: success response + summary: Update badge + tags: + - Badges + /admin/groups.json: + post: + operationId: createGroup + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + group: + additionalProperties: false + properties: + automatic_membership_email_domains: + description: pipe|separated + type: string + bio_raw: + description: About Group + type: string + default_notification_level: + type: integer + flair_bg_color: + type: string + flair_icon: + type: string + flair_upload_id: + type: integer + full_name: + type: string + muted_category_ids: + items: + type: integer + type: array + name: + type: string + owner_usernames: + description: comma,separated + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + regular_category_ids: + items: + type: integer + type: array + tracking_category_ids: + items: + type: integer + type: array + usernames: + description: comma,separated + type: string + visibility_level: + type: integer + watching_category_ids: + items: + type: integer + type: array + watching_first_post_category_ids: + items: + type: integer + type: array + required: + - name + type: object + required: + - group + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + basic_group: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_edit_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + required: + - basic_group + description: group created + summary: Create a group + tags: + - Groups + "/admin/groups/{id}.json": + delete: + operationId: deleteGroup + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + examples: + - OK + type: string + required: + - success + description: response + summary: Delete a group + tags: + - Groups + "/admin/users/list/{flag}.json": + get: + operationId: adminListUsers + parameters: + - in: path + name: flag + required: true + schema: + enum: + - active + - new + - staff + - suspended + - blocked + - suspect + type: string + - in: query + name: order + schema: + enum: + - created + - last_emailed + - seen + - username + - email + - trust_level + - days_visited + - posts_read + - topics_viewed + - posts + - read_time + type: string + - in: query + name: asc + schema: + enum: + - "true" + type: string + - in: query + name: page + schema: + type: integer + - in: query + name: show_emails + schema: + type: boolean + responses: + "200": + content: + application/json: + schema: + items: + properties: + active: + type: boolean + admin: + type: boolean + avatar_template: + type: string + created_at: + type: string + created_at_age: + type: + - number + - "null" + days_visited: + type: integer + email: + type: string + flag_level: + type: integer + id: + type: integer + last_emailed_age: + type: + - number + - "null" + last_emailed_at: + type: + - string + - "null" + last_seen_age: + type: + - number + - "null" + last_seen_at: + type: + - string + - "null" + manual_locked_trust_level: + type: + - string + - "null" + moderator: + type: boolean + name: + type: + - string + - "null" + post_count: + type: integer + posts_read_count: + type: integer + secondary_emails: + items: {} + type: array + staged: + type: boolean + time_read: + type: integer + title: + type: + - string + - "null" + topics_entered: + type: integer + trust_level: + type: integer + username: + type: string + required: + - id + - username + - name + - avatar_template + - active + - admin + - moderator + - last_seen_at + - last_emailed_at + - created_at + - last_seen_age + - last_emailed_age + - created_at_age + - trust_level + - manual_locked_trust_level + - flag_level + - title + - time_read + - staged + - days_visited + - posts_read_count + - topics_entered + - post_count + type: object + minItems: 1 + type: array + uniqueItems: true + description: response + summary: Get a list of users + tags: + - Users + - Admin + "/admin/users/{id}.json": + delete: + operationId: deleteUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + block_email: + type: boolean + block_ip: + type: boolean + block_urls: + type: boolean + delete_posts: + type: boolean + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + deleted: + type: boolean + required: + - deleted + description: response + summary: Delete a user + tags: + - Users + - Admin + get: + operationId: adminGetUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + active: + type: boolean + admin: + type: boolean + api_key_count: + type: integer + approved_by: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: + - object + - "null" + associated_accounts: + items: {} + type: array + avatar_template: + type: string + badge_count: + type: integer + bounce_score: + type: + - integer + - "null" + can_activate: + type: boolean + can_be_anonymized: + type: boolean + can_be_deleted: + type: boolean + can_be_merged: + type: boolean + can_deactivate: + type: boolean + can_delete_all_posts: + type: boolean + can_delete_sso_record: + type: boolean + can_disable_second_factor: + type: boolean + can_grant_admin: + type: boolean + can_grant_moderation: + type: boolean + can_impersonate: + type: boolean + can_revoke_admin: + type: boolean + can_revoke_moderation: + type: boolean + can_send_activation_email: + type: boolean + can_view_action_logs: + type: boolean + created_at: + type: string + created_at_age: + type: + - number + - "null" + days_visited: + type: integer + external_ids: + type: object + flag_level: + type: integer + flags_given_count: + type: integer + flags_received_count: + type: integer + full_suspend_reason: + type: + - string + - "null" + groups: + items: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + display_name: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - display_name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + type: array + id: + type: integer + ip_address: + type: string + last_emailed_age: + type: + - number + - "null" + last_emailed_at: + type: + - string + - "null" + last_seen_age: + type: + - number + - "null" + last_seen_at: + type: + - string + - "null" + like_count: + type: integer + like_given_count: + type: integer + manual_locked_trust_level: + type: + - string + - "null" + moderator: + type: boolean + name: + type: + - string + - "null" + next_penalty: + type: string + penalty_counts: + additionalProperties: false + properties: + silenced: + type: integer + suspended: + type: integer + required: + - silenced + - suspended + type: object + post_count: + type: integer + post_edits_count: + type: + - integer + - "null" + posts_read_count: + type: integer + primary_group_id: + type: + - string + - "null" + private_topics_count: + type: integer + registration_ip_address: + type: + - string + - "null" + reset_bounce_score_after: + type: + - string + - "null" + silence_reason: + type: + - string + - "null" + silenced_by: + type: + - string + - "null" + single_sign_on_record: + type: + - string + - "null" + staged: + type: boolean + suspended_by: + type: + - string + - "null" + time_read: + type: integer + title: + type: + - string + - "null" + tl3_requirements: + additionalProperties: false + properties: + days_visited: + type: integer + max_flagged_by_users: + type: integer + max_flagged_posts: + type: integer + min_days_visited: + type: integer + min_likes_given: + type: integer + min_likes_received: + type: integer + min_likes_received_days: + type: integer + min_likes_received_users: + type: integer + min_posts_read: + type: integer + min_posts_read_all_time: + type: integer + min_topics_replied_to: + type: integer + min_topics_viewed: + type: integer + min_topics_viewed_all_time: + type: integer + num_flagged_by_users: + type: integer + num_flagged_posts: + type: integer + num_likes_given: + type: integer + num_likes_received: + type: integer + num_likes_received_days: + type: integer + num_likes_received_users: + type: integer + num_topics_replied_to: + type: integer + on_grace_period: + type: boolean + penalty_counts: + additionalProperties: false + properties: + silenced: + type: integer + suspended: + type: integer + total: + type: integer + required: + - silenced + - suspended + - total + type: object + posts_read: + type: integer + posts_read_all_time: + type: integer + requirements_lost: + type: boolean + requirements_met: + type: boolean + time_period: + type: integer + topics_viewed: + type: integer + topics_viewed_all_time: + type: integer + trust_level_locked: + type: boolean + required: + - time_period + - requirements_met + - requirements_lost + - trust_level_locked + - on_grace_period + - days_visited + - min_days_visited + - num_topics_replied_to + - min_topics_replied_to + - topics_viewed + - min_topics_viewed + - posts_read + - min_posts_read + - topics_viewed_all_time + - min_topics_viewed_all_time + - posts_read_all_time + - min_posts_read_all_time + - num_flagged_posts + - max_flagged_posts + - num_flagged_by_users + - max_flagged_by_users + - num_likes_given + - min_likes_given + - num_likes_received + - min_likes_received + - num_likes_received_days + - min_likes_received_days + - num_likes_received_users + - min_likes_received_users + - penalty_counts + type: object + topic_count: + type: integer + topics_entered: + type: integer + trust_level: + type: integer + username: + type: string + warnings_received_count: + type: integer + required: + - id + - username + - name + - avatar_template + - active + - admin + - moderator + - last_seen_at + - last_emailed_at + - created_at + - last_seen_age + - last_emailed_age + - created_at_age + - trust_level + - manual_locked_trust_level + - flag_level + - title + - time_read + - staged + - days_visited + - posts_read_count + - topics_entered + - post_count + - can_send_activation_email + - can_activate + - can_deactivate + - ip_address + - registration_ip_address + - can_grant_admin + - can_revoke_admin + - can_grant_moderation + - can_revoke_moderation + - can_impersonate + - like_count + - like_given_count + - topic_count + - flags_given_count + - flags_received_count + - private_topics_count + - can_delete_all_posts + - can_be_deleted + - can_be_anonymized + - can_be_merged + - full_suspend_reason + - silence_reason + - primary_group_id + - badge_count + - warnings_received_count + - bounce_score + - reset_bounce_score_after + - can_view_action_logs + - can_disable_second_factor + - can_delete_sso_record + - api_key_count + - single_sign_on_record + - approved_by + - suspended_by + - silenced_by + - groups + - external_ids + description: response + summary: Get a user by id + tags: + - Users + - Admin + "/admin/users/{id}/anonymize.json": + put: + operationId: anonymizeUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + type: string + username: + type: string + required: + - success + - username + description: response + summary: Anonymize a user + tags: + - Users + - Admin + "/admin/users/{id}/log_out.json": + post: + operationId: logOutUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + examples: + - OK + type: string + required: + - success + description: response + summary: Log a user out + tags: + - Users + - Admin + "/admin/users/{id}/silence.json": + put: + operationId: silenceUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + message: + description: Will send an email with this message when present + type: string + post_action: + examples: + - delete + type: string + reason: + type: string + silenced_till: + examples: + - 2022-06-01T08:00:00.000Z + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + silence: + additionalProperties: false + properties: + silence_reason: + type: string + silenced: + type: boolean + silenced_at: + type: string + silenced_by: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + silenced_till: + type: string + required: + - silenced + - silence_reason + - silenced_till + - silenced_at + - silenced_by + type: object + required: + - silence + description: response + summary: Silence a user + tags: + - Users + - Admin + "/admin/users/{id}/suspend.json": + put: + operationId: suspendUser + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + message: + description: Will send an email with this message when present + type: string + post_action: + examples: + - delete + type: string + reason: + type: string + suspend_until: + examples: + - 2121-02-22 + type: string + required: + - suspend_until + - reason + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + suspension: + additionalProperties: false + properties: + full_suspend_reason: + type: string + suspend_reason: + type: string + suspended_at: + type: string + suspended_by: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + suspended_till: + type: string + required: + - suspend_reason + - full_suspend_reason + - suspended_till + - suspended_at + - suspended_by + type: object + required: + - suspension + description: response + summary: Suspend a user + tags: + - Users + - Admin + "/c/{id}/show.json": + get: + operationId: getCategory + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + category: + additionalProperties: false + properties: + all_topics_wiki: + type: boolean + allow_badges: + type: boolean + allow_global_tags: + type: boolean + allow_unlimited_owner_edits_on_first_post: + type: boolean + allowed_tag_groups: + items: {} + type: array + allowed_tags: + items: {} + type: array + auto_close_based_on_last_post: + type: boolean + auto_close_hours: + type: + - string + - "null" + available_groups: + items: {} + type: array + can_delete: + type: boolean + can_edit: + type: boolean + category_setting: + auto_bump_cooldown_days: 1 + num_auto_bump_daily: null + require_reply_approval: null + require_topic_approval: null + color: + type: string + custom_fields: + additionalProperties: false + properties: {} + type: object + default_list_filter: + type: string + default_slow_mode_seconds: + type: + - string + - "null" + default_top_period: + type: string + default_view: + type: + - string + - "null" + description: + type: + - string + - "null" + description_excerpt: + type: + - string + - "null" + description_text: + type: + - string + - "null" + email_in: + type: + - string + - "null" + email_in_allow_strangers: + type: boolean + form_template_ids: + items: {} + type: array + group_permissions: + items: + additionalProperties: false + properties: + group_name: + type: string + permission_type: + type: integer + required: + - permission_type + - group_name + type: object + type: array + has_children: + type: + - string + - "null" + id: + type: integer + mailinglist_mirror: + type: boolean + minimum_required_tags: + type: integer + name: + type: string + navigate_to_first_post_after_read: + type: boolean + notification_level: + type: integer + num_featured_topics: + type: integer + permission: + type: + - integer + - "null" + position: + type: integer + post_count: + type: integer + read_only_banner: + type: + - string + - "null" + read_restricted: + type: boolean + required_tag_groups: + items: + additionalProperties: false + properties: + min_count: + type: integer + name: + type: string + required: + - name + - min_count + type: object + type: array + search_priority: + type: integer + show_subcategory_list: + type: boolean + slug: + type: string + sort_ascending: + type: + - string + - "null" + sort_order: + type: + - string + - "null" + subcategory_list_style: + type: string + text_color: + type: string + topic_count: + type: integer + topic_featured_link_allowed: + type: boolean + topic_template: + type: + - string + - "null" + topic_url: + type: + - string + - "null" + uploaded_background: + type: + - string + - "null" + uploaded_logo: + type: + - string + - "null" + uploaded_logo_dark: + type: + - string + - "null" + required: + - id + - name + - color + - text_color + - slug + - topic_count + - post_count + - position + - description + - description_text + - description_excerpt + - topic_url + - read_restricted + - permission + - notification_level + - can_edit + - topic_template + - has_children + - sort_order + - sort_ascending + - show_subcategory_list + - num_featured_topics + - default_view + - subcategory_list_style + - default_top_period + - default_list_filter + - minimum_required_tags + - navigate_to_first_post_after_read + - custom_fields + - required_tag_groups + - read_only_banner + - available_groups + - auto_close_hours + - auto_close_based_on_last_post + - allow_unlimited_owner_edits_on_first_post + - default_slow_mode_seconds + - group_permissions + - email_in + - email_in_allow_strangers + - mailinglist_mirror + - all_topics_wiki + - can_delete + - allow_badges + - topic_featured_link_allowed + - search_priority + - uploaded_logo + - uploaded_logo_dark + - uploaded_background + type: object + required: + - category + description: response + summary: Show category + tags: + - Categories + "/c/{slug}/{id}.json": + get: + operationId: listCategoryTopics + parameters: + - in: path + name: slug + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + primary_groups: + items: {} + type: array + topic_list: + additionalProperties: false + properties: + can_create_topic: + type: boolean + per_page: + type: integer + top_tags: + items: {} + type: array + topics: + items: + additionalProperties: false + properties: + archetype: + type: string + archived: + type: boolean + bookmarked: + type: + - string + - "null" + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + excerpt: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: string + last_poster_username: + type: string + like_count: + type: integer + liked: + type: + - string + - "null" + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + additionalProperties: false + properties: + description: + type: string + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + required: + - extras + - description + - user_id + - primary_group_id + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + title: + type: string + unpinned: + type: + - string + - "null" + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + required: + - id + - title + - fancy_title + - slug + - posts_count + - reply_count + - highest_post_number + - image_url + - created_at + - last_posted_at + - bumped + - bumped_at + - archetype + - unseen + - pinned + - unpinned + - excerpt + - visible + - closed + - archived + - bookmarked + - liked + - views + - like_count + - has_summary + - last_poster_username + - category_id + - pinned_globally + - featured_link + - posters + type: object + type: array + required: + - can_create_topic + - per_page + - topics + type: object + users: + items: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + type: array + required: + - topic_list + description: success response + summary: List topics + tags: + - Categories + /categories.json: + get: + operationId: listCategories + parameters: + - in: query + name: include_subcategories + schema: + enum: + - true + type: boolean + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + category_list: + additionalProperties: false + properties: + can_create_category: + type: boolean + can_create_topic: + type: boolean + categories: + items: + additionalProperties: false + properties: + can_edit: + type: boolean + color: + type: string + default_list_filter: + type: string + default_top_period: + type: string + default_view: + type: + - string + - "null" + description: + type: + - string + - "null" + description_excerpt: + type: + - string + - "null" + description_text: + type: + - string + - "null" + has_children: + type: boolean + id: + type: integer + is_uncategorized: + type: boolean + minimum_required_tags: + type: integer + name: + type: string + navigate_to_first_post_after_read: + type: boolean + notification_level: + type: integer + num_featured_topics: + type: integer + permission: + type: integer + position: + type: integer + post_count: + type: integer + read_restricted: + type: boolean + show_subcategory_list: + type: boolean + slug: + type: string + sort_ascending: + type: + - string + - "null" + sort_order: + type: + - string + - "null" + subcategory_ids: + items: {} + type: array + subcategory_list: + items: {} + type: + - array + - "null" + subcategory_list_style: + type: string + text_color: + type: string + topic_count: + type: integer + topic_template: + type: + - string + - "null" + topic_url: + type: + - string + - "null" + topics_all_time: + type: integer + topics_day: + type: integer + topics_month: + type: integer + topics_week: + type: integer + topics_year: + type: integer + uploaded_background: + type: + - string + - "null" + uploaded_logo: + type: + - string + - "null" + uploaded_logo_dark: + type: + - string + - "null" + required: + - id + - name + - color + - text_color + - slug + - topic_count + - post_count + - position + - description + - description_text + - description_excerpt + - topic_url + - read_restricted + - permission + - notification_level + - can_edit + - topic_template + - has_children + - sort_order + - sort_ascending + - show_subcategory_list + - num_featured_topics + - default_view + - subcategory_list_style + - default_top_period + - default_list_filter + - minimum_required_tags + - navigate_to_first_post_after_read + - topics_day + - topics_week + - topics_month + - topics_year + - topics_all_time + - subcategory_ids + - uploaded_logo + - uploaded_logo_dark + - uploaded_background + type: object + type: array + required: + - can_create_category + - can_create_topic + - categories + type: object + required: + - category_list + description: success response + summary: Retrieves a list of categories + tags: + - Categories + post: + operationId: createCategory + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + allow_badges: + type: boolean + color: + examples: + - 49d9e9 + type: string + form_template_ids: + items: {} + type: array + name: + type: string + parent_category_id: + type: integer + permissions: + additionalProperties: true + properties: + everyone: + examples: + - 1 + type: integer + staff: + type: integer + type: object + search_priority: + type: integer + slug: + type: string + text_color: + examples: + - f0fcfd + type: string + topic_featured_links_allowed: + type: boolean + required: + - name + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + category: + additionalProperties: false + properties: + all_topics_wiki: + type: boolean + allow_badges: + type: boolean + allow_global_tags: + type: boolean + allow_unlimited_owner_edits_on_first_post: + type: boolean + allowed_tag_groups: + items: {} + type: array + allowed_tags: + items: {} + type: array + auto_close_based_on_last_post: + type: boolean + auto_close_hours: + type: + - string + - "null" + available_groups: + items: {} + type: array + can_delete: + type: boolean + can_edit: + type: boolean + category_setting: + auto_bump_cooldown_days: 1 + num_auto_bump_daily: null + require_reply_approval: null + require_topic_approval: null + color: + type: string + custom_fields: + additionalProperties: false + properties: {} + type: object + default_list_filter: + type: string + default_slow_mode_seconds: + type: + - string + - "null" + default_top_period: + type: string + default_view: + type: + - string + - "null" + description: + type: + - string + - "null" + description_excerpt: + type: + - string + - "null" + description_text: + type: + - string + - "null" + email_in: + type: + - string + - "null" + email_in_allow_strangers: + type: boolean + form_template_ids: + items: {} + type: array + group_permissions: + items: + additionalProperties: false + properties: + group_name: + type: string + permission_type: + type: integer + required: + - permission_type + - group_name + type: object + type: array + has_children: + type: + - string + - "null" + id: + type: integer + mailinglist_mirror: + type: boolean + minimum_required_tags: + type: integer + name: + type: string + navigate_to_first_post_after_read: + type: boolean + notification_level: + type: integer + num_featured_topics: + type: integer + permission: + type: + - integer + - "null" + position: + type: integer + post_count: + type: integer + read_only_banner: + type: + - string + - "null" + read_restricted: + type: boolean + required_tag_groups: + items: + additionalProperties: false + properties: + min_count: + type: integer + name: + type: string + required: + - name + - min_count + type: object + type: array + search_priority: + type: integer + show_subcategory_list: + type: boolean + slug: + type: string + sort_ascending: + type: + - string + - "null" + sort_order: + type: + - string + - "null" + subcategory_list_style: + type: string + text_color: + type: string + topic_count: + type: integer + topic_featured_link_allowed: + type: boolean + topic_template: + type: + - string + - "null" + topic_url: + type: + - string + - "null" + uploaded_background: + type: + - string + - "null" + uploaded_logo: + type: + - string + - "null" + uploaded_logo_dark: + type: + - string + - "null" + required: + - id + - name + - color + - text_color + - slug + - topic_count + - post_count + - position + - description + - description_text + - description_excerpt + - topic_url + - read_restricted + - permission + - notification_level + - can_edit + - topic_template + - has_children + - sort_order + - sort_ascending + - show_subcategory_list + - num_featured_topics + - default_view + - subcategory_list_style + - default_top_period + - default_list_filter + - minimum_required_tags + - navigate_to_first_post_after_read + - custom_fields + - required_tag_groups + - read_only_banner + - available_groups + - auto_close_hours + - auto_close_based_on_last_post + - allow_unlimited_owner_edits_on_first_post + - default_slow_mode_seconds + - group_permissions + - email_in + - email_in_allow_strangers + - mailinglist_mirror + - all_topics_wiki + - can_delete + - allow_badges + - topic_featured_link_allowed + - search_priority + - uploaded_logo + - uploaded_logo_dark + - uploaded_background + type: object + required: + - category + description: success response + summary: Creates a category + tags: + - Categories + "/categories/{id}.json": + put: + operationId: updateCategory + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + allow_badges: + type: boolean + color: + examples: + - 49d9e9 + type: string + form_template_ids: + items: {} + type: array + name: + type: string + parent_category_id: + type: integer + permissions: + additionalProperties: true + properties: + everyone: + examples: + - 1 + type: integer + staff: + type: integer + type: object + search_priority: + type: integer + slug: + type: string + text_color: + examples: + - f0fcfd + type: string + topic_featured_links_allowed: + type: boolean + required: + - name + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + category: + additionalProperties: false + properties: + all_topics_wiki: + type: boolean + allow_badges: + type: boolean + allow_global_tags: + type: boolean + allow_unlimited_owner_edits_on_first_post: + type: boolean + allowed_tag_groups: + items: {} + type: array + allowed_tags: + items: {} + type: array + auto_close_based_on_last_post: + type: boolean + auto_close_hours: + type: + - string + - "null" + available_groups: + items: {} + type: array + can_delete: + type: boolean + can_edit: + type: boolean + category_setting: + auto_bump_cooldown_days: 1 + num_auto_bump_daily: null + require_reply_approval: null + require_topic_approval: null + color: + type: string + custom_fields: + additionalProperties: false + properties: {} + type: object + default_list_filter: + type: string + default_slow_mode_seconds: + type: + - string + - "null" + default_top_period: + type: string + default_view: + type: + - string + - "null" + description: + type: + - string + - "null" + description_excerpt: + type: + - string + - "null" + description_text: + type: + - string + - "null" + email_in: + type: + - string + - "null" + email_in_allow_strangers: + type: boolean + form_template_ids: + items: {} + type: array + group_permissions: + items: + additionalProperties: false + properties: + group_name: + type: string + permission_type: + type: integer + required: + - permission_type + - group_name + type: object + type: array + has_children: + type: + - string + - "null" + id: + type: integer + mailinglist_mirror: + type: boolean + minimum_required_tags: + type: integer + name: + type: string + navigate_to_first_post_after_read: + type: boolean + notification_level: + type: integer + num_featured_topics: + type: integer + permission: + type: + - string + - "null" + position: + type: integer + post_count: + type: integer + read_only_banner: + type: + - string + - "null" + read_restricted: + type: boolean + required_tag_groups: + items: + additionalProperties: false + properties: + min_count: + type: integer + name: + type: string + required: + - name + - min_count + type: object + type: array + search_priority: + type: integer + show_subcategory_list: + type: boolean + slug: + type: string + sort_ascending: + type: + - string + - "null" + sort_order: + type: + - string + - "null" + subcategory_list_style: + type: string + text_color: + type: string + topic_count: + type: integer + topic_featured_link_allowed: + type: boolean + topic_template: + type: + - string + - "null" + topic_url: + type: + - string + - "null" + uploaded_background: + type: + - string + - "null" + uploaded_logo: + type: + - string + - "null" + uploaded_logo_dark: + type: + - string + - "null" + required: + - id + - name + - color + - text_color + - slug + - topic_count + - post_count + - position + - description + - description_text + - description_excerpt + - topic_url + - read_restricted + - permission + - notification_level + - can_edit + - topic_template + - form_template_ids + - has_children + - sort_order + - sort_ascending + - show_subcategory_list + - num_featured_topics + - default_view + - subcategory_list_style + - default_top_period + - default_list_filter + - minimum_required_tags + - navigate_to_first_post_after_read + - custom_fields + - required_tag_groups + - read_only_banner + - available_groups + - auto_close_hours + - auto_close_based_on_last_post + - allow_unlimited_owner_edits_on_first_post + - default_slow_mode_seconds + - group_permissions + - email_in + - email_in_allow_strangers + - mailinglist_mirror + - all_topics_wiki + - can_delete + - allow_badges + - topic_featured_link_allowed + - search_priority + - uploaded_logo + - uploaded_logo_dark + - uploaded_background + type: object + success: + type: string + required: + - success + - category + description: success response + summary: Updates a category + tags: + - Categories + /directory_items.json: + get: + operationId: listUsersPublic + parameters: + - in: query + name: period + required: true + schema: + enum: + - daily + - weekly + - monthly + - quarterly + - yearly + - all + type: string + - in: query + name: order + required: true + schema: + enum: + - likes_received + - likes_given + - topic_count + - post_count + - topics_entered + - posts_read + - days_visited + type: string + - in: query + name: asc + schema: + enum: + - "true" + type: string + - in: query + name: page + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + directory_items: + items: + additionalProperties: false + properties: + days_visited: + type: integer + id: + type: integer + likes_given: + type: integer + likes_received: + type: integer + post_count: + type: integer + posts_read: + type: integer + topic_count: + type: integer + topics_entered: + type: integer + user: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: + - string + - "null" + title: + type: + - string + - "null" + username: + type: string + required: + - id + - username + - name + - avatar_template + - title + type: object + required: + - id + - likes_received + - likes_given + - topics_entered + - topic_count + - post_count + - posts_read + - days_visited + - user + type: object + type: array + meta: + additionalProperties: false + properties: + last_updated_at: + type: + - string + - "null" + load_more_directory_items: + type: string + total_rows_directory_items: + type: integer + required: + - last_updated_at + - total_rows_directory_items + - load_more_directory_items + type: object + required: + - directory_items + - meta + description: directory items response + summary: Get a public list of users + tags: + - Users + /groups.json: + get: + operationId: listGroups + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + extras: + additionalProperties: false + properties: + type_filters: + items: {} + type: array + required: + - type_filters + type: object + groups: + items: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_edit_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + display_name: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + is_group_owner: + type: boolean + is_group_user: + type: boolean + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - display_name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + type: array + load_more_groups: + type: string + total_rows_groups: + type: integer + required: + - groups + - extras + - total_rows_groups + - load_more_groups + description: response + summary: List groups + tags: + - Groups + "/groups/{id}.json": + get: + operationId: getGroup + parameters: + - description: Use group name instead of id + example: name + in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + extras: + additionalProperties: false + properties: + visible_group_names: + items: {} + type: array + required: + - visible_group_names + type: object + group: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + allow_unknown_sender_topic_replies: + type: boolean + associated_group_ids: + items: {} + type: array + automatic: + type: boolean + automatic_membership_email_domains: + type: + - string + - "null" + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_edit_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + email_from_alias: + type: + - string + - "null" + email_password: + type: + - string + - "null" + email_username: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + imap_enabled: + type: boolean + imap_last_error: + type: + - string + - "null" + imap_mailbox_name: + type: string + imap_mailboxes: + items: {} + type: array + imap_new_emails: + type: + - string + - "null" + imap_old_emails: + type: + - string + - "null" + imap_port: + type: + - string + - "null" + imap_server: + type: + - string + - "null" + imap_ssl: + type: + - string + - "null" + imap_updated_at: + type: + - string + - "null" + imap_updated_by: + type: + - object + - "null" + incoming_email: + type: + - string + - "null" + is_group_owner_display: + type: boolean + is_group_user: + type: boolean + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable: + type: boolean + mentionable_level: + type: integer + message_count: + type: integer + messageable: + type: boolean + messageable_level: + type: integer + muted_category_ids: + items: {} + type: array + muted_tags: + items: {} + type: array + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + regular_category_ids: + items: {} + type: array + regular_tags: + items: {} + type: array + smtp_enabled: + type: boolean + smtp_port: + type: + - string + - "null" + smtp_server: + type: + - string + - "null" + smtp_ssl: + type: + - string + - "null" + smtp_updated_at: + type: + - string + - "null" + smtp_updated_by: + type: + - object + - "null" + title: + type: + - string + - "null" + tracking_category_ids: + items: {} + type: array + tracking_tags: + items: {} + type: array + user_count: + type: integer + visibility_level: + type: integer + watching_category_ids: + items: {} + type: array + watching_first_post_category_ids: + items: {} + type: array + watching_first_post_tags: + items: {} + type: array + watching_tags: + items: {} + type: array + required: + - id + - automatic + - name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - is_group_user + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + - is_group_owner_display + - mentionable + - messageable + - automatic_membership_email_domains + - smtp_server + - smtp_port + - smtp_ssl + - imap_server + - imap_port + - imap_ssl + - imap_mailbox_name + - imap_mailboxes + - email_username + - email_password + - imap_last_error + - imap_old_emails + - imap_new_emails + - message_count + - allow_unknown_sender_topic_replies + - watching_category_ids + - tracking_category_ids + - watching_first_post_category_ids + - regular_category_ids + - muted_category_ids + type: object + required: + - group + - extras + description: success response + summary: Get a group + tags: + - Groups + put: + operationId: updateGroup + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + group: + additionalProperties: false + properties: + automatic_membership_email_domains: + description: pipe|separated + type: string + bio_raw: + description: About Group + type: string + default_notification_level: + type: integer + flair_bg_color: + type: string + flair_icon: + type: string + flair_upload_id: + type: integer + full_name: + type: string + muted_category_ids: + items: + type: integer + type: array + name: + type: string + owner_usernames: + description: comma,separated + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + regular_category_ids: + items: + type: integer + type: array + tracking_category_ids: + items: + type: integer + type: array + usernames: + description: comma,separated + type: string + visibility_level: + type: integer + watching_category_ids: + items: + type: integer + type: array + watching_first_post_category_ids: + items: + type: integer + type: array + required: + - name + type: object + required: + - group + responses: + "200": + content: + application/json: + schema: + properties: + success: + examples: + - OK + type: string + type: object + description: success response + summary: Update a group + tags: + - Groups + "/groups/{id}/members.json": + delete: + operationId: removeGroupMembers + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + usernames: + description: comma separated list + examples: + - username1,username2 + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + skipped_usernames: + items: {} + type: array + success: + type: string + usernames: + items: {} + type: array + required: + - success + - usernames + - skipped_usernames + description: success response + summary: Remove group members + tags: + - Groups + get: + operationId: listGroupMembers + parameters: + - description: Use group name instead of id + example: name + in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + members: + items: + additionalProperties: false + properties: + added_at: + type: string + avatar_template: + type: string + id: + type: integer + last_posted_at: + type: string + last_seen_at: + type: string + name: + type: + - string + - "null" + timezone: + type: string + title: + type: + - string + - "null" + username: + type: string + required: + - id + - username + - name + - avatar_template + - title + - last_posted_at + - last_seen_at + - added_at + - timezone + type: object + type: array + meta: + additionalProperties: false + properties: + limit: + type: integer + offset: + type: integer + total: + type: integer + required: + - total + - limit + - offset + type: object + owners: + items: + additionalProperties: false + properties: + added_at: + type: string + avatar_template: + type: string + id: + type: integer + last_posted_at: + type: string + last_seen_at: + type: string + name: + type: + - string + - "null" + timezone: + type: string + title: + type: + - string + - "null" + username: + type: string + required: + - id + - username + - name + - avatar_template + - title + - last_posted_at + - last_seen_at + - added_at + - timezone + type: object + type: array + required: + - members + - owners + - meta + description: success response + summary: List group members + tags: + - Groups + put: + operationId: addGroupMembers + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + usernames: + description: comma separated list + examples: + - username1,username2 + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + emails: + items: {} + type: array + success: + type: string + usernames: + items: {} + type: array + required: + - success + - usernames + - emails + description: success response + summary: Add group members + tags: + - Groups + /invites.json: + post: + operationId: createInvite + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + custom_message: + description: optional, for email invites + type: string + email: + description: required for email invites only + examples: + - not-a-user-yet@example.com + type: string + expires_at: + description: |- + optional, if not supplied, the invite_expiry_days site + setting is used + type: string + group_id: + description: optional, either this or `group_names` + type: integer + group_names: + description: optional, either this or `group_id` + type: string + max_redemptions_allowed: + default: 1 + description: optional, for link invites + examples: + - 5 + type: integer + skip_email: + default: false + type: boolean + topic_id: + type: integer + type: object + responses: + "200": + content: + application/json: + schema: + properties: + created_at: + examples: + - 2021-01-01T12:00:00.000Z + type: string + custom_message: + examples: + - Hello world! + type: + - string + - "null" + email: + examples: + - not-a-user-yet@example.com + type: string + emailed: + examples: + - false + type: boolean + expired: + examples: + - false + type: boolean + expires_at: + examples: + - 2021-02-01T12:00:00.000Z + type: string + groups: + examples: + - [] + items: {} + type: array + id: + examples: + - 42 + type: integer + link: + examples: + - http://example.com/invites/9045fd767efe201ca60c6658bcf14158 + type: string + topics: + examples: + - [] + items: {} + type: array + updated_at: + examples: + - 2021-01-01T12:00:00.000Z + type: string + type: object + description: success response + summary: Create an invite + tags: + - Invites + /latest.json: + get: + operationId: listLatestTopics + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - description: |- + Enum: `default`, `created`, `activity`, `views`, `posts`, `category`, + `likes`, `op_likes`, `posters` + in: query + name: order + schema: + type: string + - description: Defaults to `desc`, add `ascending=true` to sort asc + in: query + name: ascending + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + primary_groups: + items: {} + type: array + topic_list: + properties: + can_create_topic: + type: boolean + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + per_page: + type: integer + topics: + items: + properties: + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: string + last_posted_at: + type: string + last_poster_username: + type: string + last_read_post_number: + type: integer + like_count: + type: integer + liked: + type: boolean + notification_level: + type: integer + op_like_count: + type: integer + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + properties: + description: + type: string + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + title: + type: string + unpinned: + type: + - string + - "null" + unread_posts: + type: integer + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + type: object + type: array + type: object + users: + items: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: + - string + - "null" + username: + type: string + type: object + type: array + type: object + description: topic updated + summary: Get the latest topics + tags: + - Topics + /notifications.json: + get: + operationId: getNotifications + responses: + "200": + content: + application/json: + schema: + properties: + load_more_notifications: + type: string + notifications: + items: + properties: + created_at: + type: string + data: + properties: + badge_id: + type: integer + badge_name: + type: string + badge_slug: + type: string + badge_title: + type: boolean + username: + type: string + type: object + id: + type: integer + notification_type: + type: integer + post_number: + type: + - string + - "null" + read: + type: boolean + slug: + type: + - string + - "null" + topic_id: + type: + - integer + - "null" + user_id: + type: integer + type: object + type: array + seen_notification_id: + type: integer + total_rows_notifications: + type: integer + type: object + description: notifications + summary: Get the notifications that belong to the current user + tags: + - Notifications + /notifications/mark-read.json: + put: + operationId: markNotificationsAsRead + parameters: [] + requestBody: + content: + application/json: + schema: + properties: + id: + description: |- + (optional) Leave off to mark all notifications as + read + type: integer + type: object + responses: + "200": + content: + application/json: + schema: + properties: + success: + type: string + type: object + description: notifications marked read + summary: Mark notifications as read + tags: + - Notifications + /post_actions.json: + post: + operationId: performPostAction + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + flag_topic: + type: boolean + id: + type: integer + post_action_type_id: + type: integer + required: + - id + - post_action_type_id + type: object + responses: + "200": + content: + application/json: + schema: + properties: + actions_summary: + items: + properties: + acted: + type: boolean + can_undo: + type: boolean + count: + type: integer + id: + type: integer + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: string + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + moderator: + type: boolean + name: + type: string + notice: + type: object + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: number + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + type: object + description: post updated + summary: Like a post and other actions + tags: + - Posts + /posts.json: + get: + operationId: listPosts + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - description: Load posts with an id lower than this value. Useful for pagination. + in: query + name: before + required: false + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + latest_posts: + items: + properties: + actions_summary: + items: + properties: + can_act: + type: boolean + id: + type: integer + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + category_id: + type: integer + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: string + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + moderator: + type: boolean + name: + type: string + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + raw: + type: string + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: number + staff: + type: boolean + topic_html_title: + type: string + topic_id: + type: integer + topic_slug: + type: string + topic_title: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + type: object + type: array + type: object + description: latest posts + summary: List latest posts across topics + tags: + - Posts + post: + operationId: createTopicPostPM + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + archetype: + description: Required for new private message. + examples: + - private_message + type: string + category: + description: |- + Optional if creating a new topic, and ignored if creating + a new post. + type: integer + created_at: + type: string + embed_url: + description: |- + Provide a URL from a remote system to associate a forum + topic with that URL, typically for using Discourse as a comments + system for an external blog. + type: string + external_id: + description: |- + Provide an external_id from a remote system to associate + a forum topic with that id. + type: string + raw: + type: string + target_recipients: + description: Required for private message, comma separated. + examples: + - blake,sam + type: string + target_usernames: + deprecated: true + description: Deprecated. Use target_recipients instead. + type: string + title: + description: Required if creating a new topic or new private message. + type: string + topic_id: + description: Required if creating a new post. + type: integer + required: + - raw + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + actions_summary: + items: + additionalProperties: false + properties: + can_act: + type: boolean + id: + type: integer + required: + - id + - can_act + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + bookmarked: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: + - string + - "null" + draft_sequence: + type: integer + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + mentioned_users: + items: {} + type: array + moderator: + type: boolean + name: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + raw: + type: string + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: integer + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + required: + - id + - name + - username + - avatar_template + - created_at + - cooked + - post_number + - post_type + - updated_at + - reply_count + - reply_to_post_number + - quote_count + - incoming_link_count + - reads + - readers_count + - score + - yours + - topic_id + - topic_slug + - display_username + - primary_group_name + - flair_name + - flair_url + - flair_bg_color + - flair_color + - version + - can_edit + - can_delete + - can_recover + - can_wiki + - user_title + - bookmarked + - actions_summary + - moderator + - admin + - staff + - user_id + - draft_sequence + - hidden + - trust_level + - deleted_at + - user_deleted + - edit_reason + - can_view_edit_history + - wiki + - reviewable_id + - reviewable_score_count + - reviewable_score_pending_count + description: post created + summary: Creates a new topic, a new post, or a private message + tags: + - Posts + - Topics + - Private Messages + "/posts/{id}.json": + delete: + operationId: deletePost + parameters: + - in: path + name: id + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + force_destroy: + description: |- + The `SiteSetting.can_permanently_delete` needs to be + enabled first before this param can be used. Also this endpoint + needs to be called first without `force_destroy` and then followed + up with a second call 5 minutes later with `force_destroy` to + permanently delete. + examples: + - true + type: boolean + responses: + "200": + description: success response + summary: delete a single post + tags: + - Posts + get: + description: | + This endpoint can be used to get the number of likes on a post using the + `actions_summary` property in the response. `actions_summary` responses + with the id of `2` signify a `like`. If there are no `actions_summary` + items with the id of `2`, that means there are 0 likes. Other ids likely + refer to various different flag types. + operationId: getPost + parameters: + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: true + properties: + actions_summary: + items: + additionalProperties: false + properties: + acted: + type: boolean + can_act: + type: boolean + can_undo: + type: boolean + count: + type: integer + id: + description: "`2`: like, `3`, `4`, `6`, `7`, `8`: flag" + type: integer + required: + - id + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + bookmarked: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: + - string + - "null" + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + mentioned_users: + items: {} + type: array + moderator: + type: boolean + name: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + raw: + type: string + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: {} + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + required: + - id + - username + - avatar_template + - created_at + - cooked + - post_number + - post_type + - updated_at + - reply_count + - reply_to_post_number + - quote_count + - incoming_link_count + - reads + - readers_count + - score + - yours + - topic_id + - topic_slug + - primary_group_name + - flair_name + - flair_url + - flair_bg_color + - flair_color + - version + - can_edit + - can_delete + - can_recover + - can_wiki + - user_title + - bookmarked + - raw + - actions_summary + - moderator + - admin + - staff + - user_id + - hidden + - trust_level + - deleted_at + - user_deleted + - edit_reason + - can_view_edit_history + - wiki + - reviewable_id + - reviewable_score_count + - reviewable_score_pending_count + description: single post + summary: Retrieve a single post + tags: + - Posts + put: + operationId: updatePost + parameters: + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + post: + additionalProperties: false + properties: + edit_reason: + type: string + raw: + type: string + required: + - raw + type: object + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + post: + additionalProperties: false + properties: + actions_summary: + items: + additionalProperties: false + properties: + can_act: + type: boolean + id: + type: integer + required: + - id + - can_act + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + bookmarked: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: + - string + - "null" + draft_sequence: + type: integer + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + mentioned_users: + items: {} + type: array + moderator: + type: boolean + name: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + raw: + type: string + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: {} + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + required: + - id + - username + - avatar_template + - created_at + - cooked + - post_number + - post_type + - updated_at + - reply_count + - reply_to_post_number + - quote_count + - incoming_link_count + - reads + - readers_count + - score + - yours + - topic_id + - topic_slug + - primary_group_name + - flair_name + - flair_url + - flair_bg_color + - flair_color + - version + - can_edit + - can_delete + - can_recover + - can_wiki + - user_title + - bookmarked + - raw + - actions_summary + - moderator + - admin + - staff + - user_id + - draft_sequence + - hidden + - trust_level + - deleted_at + - user_deleted + - edit_reason + - can_view_edit_history + - wiki + - reviewable_id + - reviewable_score_count + - reviewable_score_pending_count + type: object + required: + - post + description: post updated + summary: Update a single post + tags: + - Posts + "/posts/{id}/locked.json": + put: + operationId: lockPost + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + locked: + type: string + required: + - locked + type: object + responses: + "200": + content: + application/json: + schema: + properties: + locked: + type: boolean + type: object + description: post updated + summary: Lock a post from being edited + tags: + - Posts + "/posts/{id}/replies.json": + get: + operationId: postReplies + parameters: + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + properties: + actions_summary: + items: + additionalProperties: false + properties: + can_act: + type: boolean + id: + type: integer + required: + - id + - can_act + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + bookmarked: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: + - string + - "null" + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + moderator: + type: boolean + name: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: integer + reply_to_user: + additionalProperties: false + properties: + avatar_template: + type: string + name: + type: string + username: + type: string + required: + - username + - avatar_template + type: object + reviewable_id: + type: + - string + - "null" + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: integer + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + required: + - id + - name + - username + - avatar_template + - created_at + - cooked + - post_number + - post_type + - updated_at + - reply_count + - reply_to_post_number + - quote_count + - incoming_link_count + - reads + - readers_count + - score + - yours + - topic_id + - topic_slug + - display_username + - primary_group_name + - flair_name + - flair_url + - flair_bg_color + - flair_color + - version + - can_edit + - can_delete + - can_recover + - can_wiki + - user_title + - reply_to_user + - bookmarked + - actions_summary + - moderator + - admin + - staff + - user_id + - hidden + - trust_level + - deleted_at + - user_deleted + - edit_reason + - can_view_edit_history + - wiki + - reviewable_id + - reviewable_score_count + - reviewable_score_pending_count + type: object + minItems: 1 + type: array + uniqueItems: true + description: post replies + summary: List replies to a post + tags: + - Posts + /search.json: + get: + operationId: search + parameters: + - description: | + The query string needs to be url encoded and is made up of the following options: + - Search term. This is just a string. Usually it would be the first item in the query. + - `@`: Use the `@` followed by the username to specify posts by this user. + - `#`: Use the `#` followed by the category slug to search within this category. + - `tags:`: `api,solved` or for posts that have all the specified tags `api+solved`. + - `before:`: `yyyy-mm-dd` + - `after:`: `yyyy-mm-dd` + - `order:`: `latest`, `likes`, `views`, `latest_topic` + - `assigned:`: username (without `@`) + - `in:`: `title`, `likes`, `personal`, `messages`, `seen`, `unseen`, `posted`, `created`, `watching`, `tracking`, `bookmarks`, `assigned`, `unassigned`, `first`, `pinned`, `wiki` + - `with:`: `images` + - `status:`: `open`, `closed`, `public`, `archived`, `noreplies`, `single_user`, `solved`, `unsolved` + - `group:`: group_name or group_id + - `group_messages:`: group_name or group_id + - `min_posts:`: 1 + - `max_posts:`: 10 + - `min_views:`: 1 + - `max_views:`: 10 + + If you are using cURL you can use the `-G` and the `--data-urlencode` flags to encode the query: + + ``` + curl -i -sS -X GET -G "http://localhost:4200/search.json" \ + --data-urlencode 'q=wordpress @scossar #fun after:2020-01-01' + ``` + example: |- + api @blake #support tags:api after:2021-06-04 in:unseen in:open + order:latest_topic + in: query + name: q + schema: + type: string + - example: 1 + in: query + name: page + schema: + type: integer + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + categories: + items: {} + type: array + grouped_search_result: + additionalProperties: false + properties: + can_create_topic: + type: boolean + category_ids: + items: {} + type: array + error: + type: + - string + - "null" + group_ids: + items: {} + type: array + more_categories: + type: + - string + - "null" + more_full_page_results: + type: + - string + - "null" + more_posts: + type: + - string + - "null" + more_users: + type: + - string + - "null" + post_ids: + items: {} + type: array + search_log_id: + type: integer + tag_ids: + items: {} + type: array + term: + type: string + user_ids: + items: {} + type: array + required: + - more_posts + - more_users + - more_categories + - term + - search_log_id + - more_full_page_results + - can_create_topic + - error + - post_ids + - user_ids + - category_ids + - tag_ids + - group_ids + type: object + groups: + items: {} + type: array + posts: + items: {} + type: array + tags: + items: {} + type: array + users: + items: {} + type: array + required: + - posts + - users + - categories + - tags + - groups + - grouped_search_result + description: success response + summary: Search for a term + tags: + - Search + /session/forgot_password.json: + post: + operationId: sendPasswordResetEmail + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + login: + type: string + required: + - login + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + type: string + user_found: + type: boolean + required: + - success + - user_found + description: success response + summary: Send password reset email + tags: + - Users + /site.json: + get: + description: Can be used to fetch all categories and subcategories + operationId: getSite + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + anonymous_top_menu_items: + items: {} + type: array + archetypes: + items: + additionalProperties: false + properties: + id: + type: string + name: + type: string + options: + items: {} + type: array + required: + - id + - name + - options + type: object + type: array + auth_providers: + items: {} + type: array + can_associate_groups: + type: boolean + can_create_tag: + type: boolean + can_tag_pms: + type: boolean + can_tag_topics: + type: boolean + categories: + items: + additionalProperties: false + properties: + allow_global_tags: + type: boolean + allowed_tag_groups: + items: {} + type: array + allowed_tags: + items: {} + type: array + can_edit: + type: boolean + color: + type: string + custom_fields: + additionalProperties: true + type: + - object + - "null" + default_list_filter: + type: string + default_top_period: + type: string + default_view: + type: + - string + - "null" + description: + type: + - string + - "null" + description_excerpt: + type: + - string + - "null" + description_text: + type: + - string + - "null" + form_template_ids: + items: {} + type: array + has_children: + type: boolean + id: + type: integer + minimum_required_tags: + type: integer + name: + type: string + navigate_to_first_post_after_read: + type: boolean + notification_level: + type: integer + num_featured_topics: + type: integer + parent_category_id: + type: integer + permission: + type: integer + position: + type: integer + post_count: + type: integer + read_only_banner: + type: + - string + - "null" + read_restricted: + type: boolean + required_tag_groups: + items: + additionalProperties: false + properties: + min_count: + type: integer + name: + type: string + required: + - name + - min_count + type: object + type: array + show_subcategory_list: + type: boolean + slug: + type: string + sort_ascending: + type: + - string + - "null" + sort_order: + type: + - string + - "null" + subcategory_list_style: + type: string + text_color: + type: string + topic_count: + type: integer + topic_template: + type: + - string + - "null" + topic_url: + type: string + uploaded_background: + type: + - string + - "null" + uploaded_logo: + type: + - string + - "null" + uploaded_logo_dark: + type: + - string + - "null" + required: + - id + - name + - color + - text_color + - slug + - topic_count + - post_count + - position + - topic_url + - read_restricted + - permission + - notification_level + - topic_template + - has_children + - sort_order + - sort_ascending + - show_subcategory_list + - num_featured_topics + - default_view + - subcategory_list_style + - default_top_period + - default_list_filter + - minimum_required_tags + - navigate_to_first_post_after_read + - allowed_tags + - allowed_tag_groups + - allow_global_tags + - required_tag_groups + - read_only_banner + - uploaded_logo + - uploaded_logo_dark + - uploaded_background + - can_edit + type: object + type: array + censored_regexp: + items: + type: object + type: array + custom_emoji_translation: + additionalProperties: false + properties: {} + type: object + default_archetype: + type: string + default_dark_color_scheme: + type: + - object + - "null" + denied_emojis: + type: array + displayed_about_plugin_stat_groups: + type: array + filters: + items: {} + type: array + groups: + items: + additionalProperties: false + properties: + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + id: + type: integer + name: + type: string + required: + - id + - name + - flair_url + - flair_bg_color + - flair_color + type: object + type: array + hashtag_configurations: + type: object + hashtag_icons: + type: array + markdown_additional_options: + type: object + notification_types: + additionalProperties: false + properties: + assigned: + type: integer + bookmark_reminder: + type: integer + chat_group_mention: + type: integer + chat_invitation: + type: integer + chat_mention: + type: integer + chat_message: + type: integer + chat_quoted: + type: integer + circles_activity: + type: integer + code_review_commit_approved: + type: integer + custom: + type: integer + edited: + type: integer + event_invitation: + type: integer + event_reminder: + type: integer + following: + type: integer + following_created_topic: + type: integer + following_replied: + type: integer + granted_badge: + type: integer + group_mentioned: + type: integer + group_message_summary: + type: integer + invited_to_private_message: + type: integer + invited_to_topic: + type: integer + invitee_accepted: + type: integer + liked: + type: integer + liked_consolidated: + type: integer + linked: + type: integer + membership_request_accepted: + type: integer + membership_request_consolidated: + type: integer + mentioned: + type: integer + moved_post: + type: integer + new_features: + type: integer + post_approved: + type: integer + posted: + type: integer + private_message: + type: integer + question_answer_user_commented: + type: integer + quoted: + type: integer + reaction: + type: integer + replied: + type: integer + topic_reminder: + type: integer + votes_released: + type: integer + watching_category_or_tag: + type: integer + watching_first_post: + type: integer + required: + - mentioned + - replied + - quoted + - edited + - liked + - private_message + - invited_to_private_message + - invitee_accepted + - posted + - watching_category_or_tag + - moved_post + - linked + - granted_badge + - invited_to_topic + - custom + - group_mentioned + - group_message_summary + - watching_first_post + - topic_reminder + - liked_consolidated + - post_approved + - code_review_commit_approved + - membership_request_accepted + - membership_request_consolidated + - bookmark_reminder + - reaction + - votes_released + - event_reminder + - event_invitation + - chat_mention + - chat_message + - chat_invitation + - chat_group_mention + type: object + periods: + items: {} + type: array + post_action_types: + items: + additionalProperties: false + properties: + description: + type: string + id: + type: + - integer + - "null" + is_custom_flag: + type: boolean + is_flag: + type: boolean + name: + type: string + name_key: + type: + - string + - "null" + short_description: + type: string + required: + - id + - name_key + - name + - description + - short_description + - is_flag + - is_custom_flag + type: object + type: array + post_types: + additionalProperties: false + properties: + moderator_action: + type: integer + regular: + type: integer + small_action: + type: integer + whisper: + type: integer + required: + - regular + - moderator_action + - small_action + - whisper + type: object + show_welcome_topic_banner: + type: boolean + tags_filter_regexp: + type: string + top_menu_items: + items: {} + type: array + top_tags: + items: {} + type: array + topic_featured_link_allowed_category_ids: + items: {} + type: array + topic_flag_types: + items: + additionalProperties: false + properties: + description: + type: string + id: + type: + - integer + - "null" + is_custom_flag: + type: boolean + is_flag: + type: boolean + name: + type: string + name_key: + type: + - string + - "null" + short_description: + type: string + required: + - id + - name_key + - name + - description + - short_description + - is_flag + - is_custom_flag + type: object + type: array + trust_levels: + additionalProperties: false + properties: + basic: + type: integer + leader: + type: integer + member: + type: integer + newuser: + type: integer + regular: + type: integer + required: + - newuser + - basic + - member + - regular + - leader + type: object + uncategorized_category_id: + type: integer + user_color_schemes: + items: + additionalProperties: false + properties: + id: + type: integer + is_dark: + type: boolean + name: + type: string + required: + - id + - name + - is_dark + type: object + type: array + user_field_max_length: + type: integer + user_fields: + items: {} + type: array + user_themes: + items: + additionalProperties: false + properties: + color_scheme_id: + type: + - integer + - "null" + default: + type: boolean + name: + type: string + theme_id: + type: integer + required: + - theme_id + - name + - default + - color_scheme_id + type: object + type: array + watched_words_link: + type: + - string + - "null" + watched_words_replace: + type: + - string + - "null" + whispers_allowed_groups_names: + type: array + wizard_required: + type: boolean + required: + - default_archetype + - notification_types + - post_types + - trust_levels + - groups + - filters + - periods + - top_menu_items + - anonymous_top_menu_items + - uncategorized_category_id + - user_field_max_length + - post_action_types + - topic_flag_types + - can_create_tag + - can_tag_topics + - can_tag_pms + - tags_filter_regexp + - top_tags + - topic_featured_link_allowed_category_ids + - user_themes + - user_color_schemes + - default_dark_color_scheme + - censored_regexp + - custom_emoji_translation + - watched_words_replace + - watched_words_link + - categories + - archetypes + - user_fields + - auth_providers + description: success response + summary: Get site info + tags: + - Site + - Categories + "/t/-/{id}.json": + put: + operationId: updateTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + topic: + properties: + category_id: + type: integer + title: + type: string + type: object + type: object + responses: + "200": + content: + application/json: + schema: + properties: + basic_topic: + properties: + fancy_title: + type: string + id: + type: integer + posts_count: + type: integer + slug: + type: string + title: + type: string + type: object + type: object + description: topic updated + summary: Update a topic + tags: + - Topics + "/t/external_id/{external_id}.json": + get: + operationId: getTopicByExternalId + parameters: + - in: path + name: external_id + required: true + schema: + type: string + responses: + "301": + description: redirects to /t/{topic_id}.json + summary: Get topic by external_id + tags: + - Topics + "/t/{id}.json": + delete: + operationId: removeTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + description: specific posts + summary: Remove a topic + tags: + - Topics + get: + operationId: getTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + actions_summary: + items: + additionalProperties: false + properties: + can_act: + type: boolean + count: + type: integer + hidden: + type: boolean + id: + type: integer + required: + - id + - count + - hidden + - can_act + type: object + type: array + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bookmarks: + items: {} + type: array + category_id: + type: integer + chunk_size: + type: integer + closed: + type: boolean + created_at: + type: string + current_post_number: + type: integer + deleted_at: + type: + - string + - "null" + deleted_by: + type: + - string + - "null" + details: + additionalProperties: false + properties: + can_archive_topic: + type: boolean + can_close_topic: + type: boolean + can_convert_topic: + type: boolean + can_create_post: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_edit_staff_notes: + type: boolean + can_flag_topic: + type: boolean + can_invite_to: + type: boolean + can_invite_via_email: + type: boolean + can_moderate_category: + type: boolean + can_move_posts: + type: boolean + can_pin_unpin_topic: + type: boolean + can_remove_allowed_users: + type: boolean + can_remove_self_id: + type: integer + can_reply_as_new_topic: + type: boolean + can_review_topic: + type: boolean + can_split_merge_topic: + type: boolean + can_toggle_topic_visibility: + type: boolean + created_by: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + last_poster: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + notification_level: + type: integer + participants: + items: + additionalProperties: false + properties: + admin: + type: boolean + avatar_template: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + id: + type: integer + moderator: + type: boolean + name: + type: string + post_count: + type: integer + primary_group_name: + type: + - string + - "null" + trust_level: + type: integer + username: + type: string + required: + - id + - username + - name + - avatar_template + - post_count + - primary_group_name + - flair_name + - flair_url + - flair_color + - flair_bg_color + - admin + - moderator + - trust_level + type: object + type: array + required: + - can_edit + - notification_level + - can_move_posts + - can_delete + - can_remove_allowed_users + - can_create_post + - can_reply_as_new_topic + - can_convert_topic + - can_review_topic + - can_close_topic + - can_archive_topic + - can_split_merge_topic + - can_edit_staff_notes + - can_toggle_topic_visibility + - can_pin_unpin_topic + - can_moderate_category + - can_remove_self_id + - created_by + - last_poster + type: object + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_deleted: + type: boolean + has_summary: + type: boolean + highest_post_number: + type: + - integer + - "null" + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: + - string + - "null" + like_count: + type: integer + message_bus_last_id: + type: integer + participant_count: + type: integer + pinned: + type: boolean + pinned_at: + type: + - string + - "null" + pinned_globally: + type: boolean + pinned_until: + type: + - string + - "null" + post_stream: + additionalProperties: false + properties: + posts: + items: + additionalProperties: false + properties: + actions_summary: + items: + additionalProperties: false + properties: + can_act: + type: boolean + id: + type: integer + required: + - id + - can_act + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + bookmarked: + type: boolean + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: string + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + link_counts: + items: + additionalProperties: false + properties: + clicks: + type: integer + internal: + type: boolean + reflection: + type: boolean + title: + type: string + url: + type: string + required: + - url + - internal + - reflection + - title + - clicks + type: object + type: array + moderator: + type: boolean + name: + type: string + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + read: + type: boolean + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: integer + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: integer + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + required: + - id + - name + - username + - avatar_template + - created_at + - cooked + - post_number + - post_type + - updated_at + - reply_count + - reply_to_post_number + - quote_count + - incoming_link_count + - reads + - readers_count + - score + - yours + - topic_id + - topic_slug + - display_username + - primary_group_name + - flair_name + - flair_url + - flair_bg_color + - flair_color + - version + - can_edit + - can_delete + - can_recover + - can_wiki + - link_counts + - read + - user_title + - bookmarked + - actions_summary + - moderator + - admin + - staff + - user_id + - hidden + - trust_level + - deleted_at + - user_deleted + - edit_reason + - can_view_edit_history + - wiki + - reviewable_id + - reviewable_score_count + - reviewable_score_pending_count + type: object + type: array + stream: + items: {} + type: array + required: + - posts + - stream + type: object + posts_count: + type: integer + reply_count: + type: integer + show_read_indicator: + type: boolean + slow_mode_enabled_until: + type: + - string + - "null" + slow_mode_seconds: + type: integer + slug: + type: string + suggested_topics: + items: + additionalProperties: false + properties: + archetype: + type: string + archived: + type: boolean + bookmarked: + type: + - string + - "null" + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + excerpt: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: + - string + - "null" + like_count: + type: integer + liked: + type: + - string + - "null" + pinned: + type: boolean + posters: + items: + additionalProperties: false + properties: + description: + type: string + extras: + type: string + user: + additionalProperties: false + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + required: + - id + - username + - name + - avatar_template + type: object + required: + - extras + - description + - user + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + tags: + items: {} + type: array + tags_descriptions: + additionalProperties: false + properties: {} + type: object + title: + type: string + unpinned: + type: + - string + - "null" + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + required: + - id + - title + - fancy_title + - slug + - posts_count + - reply_count + - highest_post_number + - image_url + - created_at + - last_posted_at + - bumped + - bumped_at + - archetype + - unseen + - pinned + - unpinned + - excerpt + - visible + - closed + - archived + - bookmarked + - liked + - tags + - tags_descriptions + - like_count + - views + - category_id + - featured_link + - posters + type: object + type: array + tags: + items: {} + type: array + tags_descriptions: + additionalProperties: false + properties: {} + type: object + thumbnails: + type: + - string + - "null" + timeline_lookup: + items: {} + type: array + title: + type: string + topic_timer: + type: + - string + - "null" + unpinned: + type: + - string + - "null" + user_id: + type: integer + views: + type: integer + visible: + type: boolean + word_count: + type: + - integer + - "null" + required: + - post_stream + - timeline_lookup + - suggested_topics + - tags + - tags_descriptions + - id + - title + - fancy_title + - posts_count + - created_at + - views + - reply_count + - like_count + - last_posted_at + - visible + - closed + - archived + - has_summary + - archetype + - slug + - category_id + - word_count + - deleted_at + - user_id + - featured_link + - pinned_globally + - pinned_at + - pinned_until + - image_url + - slow_mode_seconds + - draft + - draft_key + - draft_sequence + - unpinned + - pinned + - highest_post_number + - deleted_by + - has_deleted + - actions_summary + - chunk_size + - bookmarked + - bookmarks + - topic_timer + - message_bus_last_id + - participant_count + - show_read_indicator + - thumbnails + - slow_mode_enabled_until + - details + description: specific posts + summary: Get a single topic + tags: + - Topics + "/t/{id}/bookmark.json": + put: + operationId: bookmarkTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + description: topic updated + summary: Bookmark topic + tags: + - Topics + "/t/{id}/change-timestamp.json": + put: + operationId: updateTopicTimestamp + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + timestamp: + examples: + - "1594291380" + type: string + required: + - timestamp + type: object + responses: + "200": + content: + application/json: + schema: + properties: + success: + examples: + - OK + type: string + type: object + description: topic updated + summary: Update topic timestamp + tags: + - Topics + "/t/{id}/invite.json": + post: + operationId: inviteToTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + email: + type: string + user: + type: string + type: object + responses: + "200": + content: + application/json: + schema: + properties: + user: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + type: object + type: object + description: topic updated + summary: Invite to topic + tags: + - Topics + - Invites + "/t/{id}/notifications.json": + post: + operationId: setNotificationLevel + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + notification_level: + enum: + - "0" + - "1" + - "2" + - "3" + type: string + required: + - notification_level + type: object + responses: + "200": + content: + application/json: + schema: + properties: + success: + examples: + - OK + type: string + type: object + description: topic updated + summary: Set notification level + tags: + - Topics + "/t/{id}/posts.json": + get: + operationId: getSpecificPostsFromTopic + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string +# requestBody: +# content: +# application/json: +# schema: +# properties: +# "post_ids[]": +# type: integer +# required: +# - post_ids[] +# type: object + responses: + "200": + content: + application/json: + schema: + properties: + id: + type: integer + post_stream: + properties: + posts: + items: + properties: + actions_summary: + items: + properties: + can_act: + type: boolean + id: + type: integer + type: object + type: array + admin: + type: boolean + avatar_template: + type: string + can_delete: + type: boolean + can_edit: + type: boolean + can_recover: + type: boolean + can_view_edit_history: + type: boolean + can_wiki: + type: boolean + cooked: + type: string + created_at: + type: string + deleted_at: + type: + - string + - "null" + display_username: + type: + - string + - "null" + edit_reason: + type: + - string + - "null" + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + hidden: + type: boolean + id: + type: integer + incoming_link_count: + type: integer + moderator: + type: boolean + name: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: integer + primary_group_name: + type: + - string + - "null" + quote_count: + type: integer + read: + type: boolean + readers_count: + type: integer + reads: + type: integer + reply_count: + type: integer + reply_to_post_number: + type: + - string + - "null" + reviewable_id: + type: integer + reviewable_score_count: + type: integer + reviewable_score_pending_count: + type: integer + score: + type: integer + staff: + type: boolean + topic_id: + type: integer + topic_slug: + type: string + trust_level: + type: integer + updated_at: + type: string + user_deleted: + type: boolean + user_id: + type: integer + user_title: + type: + - string + - "null" + username: + type: string + version: + type: integer + wiki: + type: boolean + yours: + type: boolean + type: object + type: array + type: object + type: object + description: specific posts + summary: Get specific posts from a topic + tags: + - Topics + "/t/{id}/status.json": + put: + operationId: updateTopicStatus + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + enabled: + enum: + - "true" + - "false" + type: string + status: + enum: + - closed + - pinned + - pinned_globally + - archived + - visible + type: string + until: + description: Only required for `pinned` and `pinned_globally` + examples: + - 2030-12-31 + type: string + required: + - status + - enabled + type: object + responses: + "200": + content: + application/json: + schema: + properties: + success: + examples: + - OK + type: string + topic_status_update: + type: + - string + - "null" + type: object + description: topic updated + summary: Update the status of a topic + tags: + - Topics + "/t/{id}/timer.json": + post: + operationId: createTopicTimer + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + based_on_last_post: + type: boolean + category_id: + type: integer + status_type: + type: string + time: + examples: + - "" + type: string + type: object + responses: + "200": + content: + application/json: + schema: + properties: + based_on_last_post: + type: boolean + category_id: + type: + - string + - "null" + closed: + type: boolean + duration: + type: + - string + - "null" + execute_at: + type: string + success: + examples: + - OK + type: string + type: object + description: topic updated + summary: Create topic timer + tags: + - Topics + "/tag/{name}.json": + get: + operationId: getTag + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + primary_groups: + items: {} + type: array + topic_list: + properties: + can_create_topic: + type: boolean + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + per_page: + type: integer + tags: + items: + properties: + id: + type: integer + name: + type: string + staff: + type: boolean + topic_count: + type: integer + type: object + type: array + topics: + items: + properties: + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: string + last_poster_username: + type: string + last_read_post_number: + type: integer + like_count: + type: integer + liked: + type: boolean + notification_level: + type: integer + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + properties: + description: + type: string + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + tags: + items: {} + type: array + title: + type: string + unpinned: + type: + - string + - "null" + unread_posts: + type: integer + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + type: object + type: array + type: object + users: + items: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: + - string + - "null" + username: + type: string + type: object + type: array + type: object + description: notifications + summary: Get a specific tag + tags: + - Tags + /tag_groups.json: + get: + operationId: listTagGroups + responses: + "200": + content: + application/json: + schema: + properties: + tag_groups: + items: + properties: + id: + type: integer + name: + type: string + one_per_topic: + type: boolean + parent_tag_name: + items: {} + type: array + permissions: + properties: + staff: + type: integer + type: object + tag_names: + items: {} + type: array + type: object + type: array + type: object + description: tags + summary: Get a list of tag groups + tags: + - Tags + post: + operationId: createTagGroup + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + name: + type: string + required: + - name + type: object + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + tag_group: + properties: + id: + type: integer + name: + type: string + one_per_topic: + type: boolean + parent_tag_name: + items: {} + type: array + permissions: + type: object + tag_names: + items: {} + type: array + required: + - id + - name + - tag_names + - parent_tag_name + - one_per_topic + - permissions + type: object + required: + - tag_group + type: object + description: tag group created + summary: Creates a tag group + tags: + - Tags + "/tag_groups/{id}.json": + get: + operationId: getTagGroup + parameters: + - in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + tag_group: + properties: + id: + type: integer + name: + type: string + one_per_topic: + type: boolean + parent_tag_name: + items: {} + type: array + permissions: + properties: + everyone: + type: integer + type: object + tag_names: + items: {} + type: array + type: object + type: object + description: notifications + summary: Get a single tag group + tags: + - Tags + put: + operationId: updateTagGroup + parameters: + - in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + type: object + responses: + "200": + content: + application/json: + schema: + properties: + success: + type: string + tag_group: + properties: + id: + type: integer + name: + type: string + one_per_topic: + type: boolean + parent_tag_name: + items: {} + type: array + permissions: + properties: + everyone: + type: integer + type: object + tag_names: + items: {} + type: array + type: object + type: object + description: Tag group updated + summary: Update tag group + tags: + - Tags + /tags.json: + get: + operationId: listTags + responses: + "200": + content: + application/json: + schema: + properties: + extras: + properties: + categories: + items: {} + type: array + type: object + tags: + items: + properties: + count: + type: integer + id: + type: string + pm_count: + type: integer + target_tag: + type: + - string + - "null" + text: + type: string + type: object + type: array + type: object + description: notifications + summary: Get a list of tags + tags: + - Tags + /top.json: + get: + operationId: listTopTopics + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - description: "Enum: `all`, `yearly`, `quarterly`, `monthly`, `weekly`, `daily`" + in: query + name: period + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + primary_groups: + items: {} + type: array + topic_list: + properties: + can_create_topic: + type: boolean + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + for_period: + type: string + per_page: + type: integer + topics: + items: + properties: + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: string + last_poster_username: + type: string + last_read_post_number: + type: integer + like_count: + type: integer + liked: + type: boolean + notification_level: + type: integer + op_like_count: + type: integer + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + properties: + description: + type: string + extras: + type: + - string + - "null" + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + title: + type: string + unpinned: + type: boolean + unread_posts: + type: integer + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + type: object + type: array + type: object + users: + items: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + type: object + type: array + type: object + description: response + summary: Get the top topics filtered by period + tags: + - Topics + "/topics/private-messages-sent/{username}.json": + get: + operationId: getUserSentPrivateMessages + parameters: + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + primary_groups: + items: {} + type: array + topic_list: + properties: + can_create_topic: + type: boolean + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + per_page: + type: integer + topics: + items: + properties: + allowed_user_count: + type: integer + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: + - string + - "null" + closed: + type: boolean + created_at: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: string + last_poster_username: + type: string + last_read_post_number: + type: integer + like_count: + type: integer + liked: + type: boolean + notification_level: + type: integer + participants: + items: {} + type: array + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + properties: + description: + type: string + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + title: + type: string + unpinned: + type: + - string + - "null" + unread_posts: + type: integer + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + type: object + type: array + type: object + users: + items: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: + - string + - "null" + username: + type: string + type: object + type: array + type: object + description: private messages + summary: Get a list of private messages sent for a user + tags: + - Private Messages + "/topics/private-messages/{username}.json": + get: + operationId: listUserPrivateMessages + parameters: + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + primary_groups: + items: {} + type: array + topic_list: + properties: + can_create_topic: + type: boolean + draft: + type: + - string + - "null" + draft_key: + type: string + draft_sequence: + type: integer + per_page: + type: integer + topics: + items: + properties: + allowed_user_count: + type: integer + archetype: + type: string + archived: + type: boolean + bookmarked: + type: boolean + bumped: + type: boolean + bumped_at: + type: string + category_id: + type: + - string + - "null" + closed: + type: boolean + created_at: + type: string + fancy_title: + type: string + featured_link: + type: + - string + - "null" + has_summary: + type: boolean + highest_post_number: + type: integer + id: + type: integer + image_url: + type: + - string + - "null" + last_posted_at: + type: string + last_poster_username: + type: string + last_read_post_number: + type: integer + like_count: + type: integer + liked: + type: boolean + notification_level: + type: integer + participants: + items: + properties: + description: + type: + - string + - "null" + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + pinned: + type: boolean + pinned_globally: + type: boolean + posters: + items: + properties: + description: + type: string + extras: + type: string + primary_group_id: + type: + - string + - "null" + user_id: + type: integer + type: object + type: array + posts_count: + type: integer + reply_count: + type: integer + slug: + type: string + title: + type: string + unpinned: + type: + - string + - "null" + unread_posts: + type: integer + unseen: + type: boolean + views: + type: integer + visible: + type: boolean + type: object + type: array + type: object + users: + items: + properties: + avatar_template: + type: string + id: + type: integer + name: + type: string + username: + type: string + type: object + type: array + type: object + description: private messages + summary: Get a list of private messages for a user + tags: + - Private Messages + "/u/by-external/{external_id}.json": + get: + operationId: getUserExternalId + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: external_id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + user: + additionalProperties: false + properties: + admin: + type: boolean + allowed_pm_usernames: + items: {} + type: array + avatar_template: + type: string + badge_count: + type: integer + can_be_deleted: + type: boolean + can_change_bio: + type: boolean + can_change_location: + type: boolean + can_change_tracking_preferences: + type: boolean + can_change_website: + type: boolean + can_delete_all_posts: + type: boolean + can_edit: + type: boolean + can_edit_email: + type: boolean + can_edit_name: + type: boolean + can_edit_username: + type: boolean + can_ignore_user: + type: boolean + can_mute_user: + type: boolean + can_send_private_message_to_user: + type: boolean + can_send_private_messages: + type: boolean + can_upload_profile_header: + type: boolean + can_upload_user_card_background: + type: boolean + created_at: + type: string + custom_fields: + additionalProperties: false + properties: + first_name: + type: + - string + - "null" + type: object + featured_topic: + type: + - string + - "null" + featured_user_badge_ids: + items: {} + type: array + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_group_id: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + group_users: + items: + additionalProperties: false + properties: + group_id: + type: integer + notification_level: + type: integer + owner: + type: boolean + user_id: + type: integer + required: + - group_id + - user_id + - notification_level + type: object + type: array + groups: + items: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + display_name: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - display_name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + type: array + has_title_badges: + type: boolean + id: + type: integer + ignored: + type: boolean + ignored_usernames: + items: {} + type: array + invited_by: + type: + - string + - "null" + last_posted_at: + type: + - string + - "null" + last_seen_at: + type: + - string + - "null" + locale: + type: + - string + - "null" + mailing_list_posts_per_day: + type: integer + moderator: + type: boolean + muted: + type: boolean + muted_category_ids: + items: {} + type: array + muted_tags: + items: {} + type: array + muted_usernames: + items: {} + type: array + name: + type: string + pending_count: + type: integer + pending_posts_count: + type: integer + post_count: + type: integer + primary_group_id: + type: + - string + - "null" + primary_group_name: + type: + - string + - "null" + profile_view_count: + type: integer + recent_time_read: + type: integer + regular_category_ids: + items: {} + type: array + second_factor_backup_enabled: + type: boolean + second_factor_enabled: + type: boolean + staged: + type: boolean + system_avatar_template: + type: string + system_avatar_upload_id: + type: + - string + - "null" + time_read: + type: integer + title: + type: + - string + - "null" + tracked_category_ids: + items: {} + type: array + tracked_tags: + items: {} + type: array + trust_level: + type: integer + uploaded_avatar_id: + type: + - string + - "null" + use_logo_small_as_avatar: + type: boolean + user_api_keys: + type: + - string + - "null" + user_auth_tokens: + items: + additionalProperties: false + properties: + browser: + type: string + client_ip: + type: string + created_at: + type: string + device: + type: string + icon: + type: string + id: + type: integer + is_active: + type: boolean + location: + type: string + os: + type: string + seen_at: + type: string + required: + - id + - client_ip + - location + - browser + - device + - os + - icon + - created_at + - seen_at + - is_active + type: object + type: array + user_fields: + additionalProperties: false + properties: + "1": + type: + - string + - "null" + "2": + type: + - string + - "null" + required: + - "1" + - "2" + type: object + user_notification_schedule: + additionalProperties: false + properties: + day_0_end_time: + type: integer + day_0_start_time: + type: integer + day_1_end_time: + type: integer + day_1_start_time: + type: integer + day_2_end_time: + type: integer + day_2_start_time: + type: integer + day_3_end_time: + type: integer + day_3_start_time: + type: integer + day_4_end_time: + type: integer + day_4_start_time: + type: integer + day_5_end_time: + type: integer + day_5_start_time: + type: integer + day_6_end_time: + type: integer + day_6_start_time: + type: integer + enabled: + type: boolean + required: + - enabled + - day_0_start_time + - day_0_end_time + - day_1_start_time + - day_1_end_time + - day_2_start_time + - day_2_end_time + - day_3_start_time + - day_3_end_time + - day_4_start_time + - day_4_end_time + - day_5_start_time + - day_5_end_time + - day_6_start_time + - day_6_end_time + type: object + user_option: + additionalProperties: false + properties: + allow_private_messages: + type: boolean + auto_track_topics_after_msecs: + type: integer + automatically_unpin_topics: + type: boolean + bookmark_auto_delete_preference: + type: integer + color_scheme_id: + type: + - string + - "null" + dark_scheme_id: + type: + - string + - "null" + default_calendar: + type: string + digest_after_minutes: + type: integer + dynamic_favicon: + type: boolean + email_digests: + type: boolean + email_in_reply_to: + type: boolean + email_level: + type: integer + email_messages_level: + type: integer + email_previous_replies: + type: integer + enable_allowed_pm_users: + type: boolean + enable_defer: + type: boolean + enable_quoting: + type: boolean + external_links_in_new_tab: + type: boolean + hide_profile_and_presence: + type: boolean + homepage_id: + type: + - string + - "null" + include_tl0_in_digests: + type: boolean + like_notification_frequency: + type: integer + mailing_list_mode: + type: boolean + mailing_list_mode_frequency: + type: integer + new_topic_duration_minutes: + type: integer + notification_level_when_replying: + type: integer + oldest_search_log_date: + type: + - string + - "null" + seen_popups: + type: + - array + - "null" + sidebar_list_destination: + type: string + skip_new_user_tips: + type: boolean + text_size: + type: string + text_size_seq: + type: integer + theme_ids: + items: {} + type: array + theme_key_seq: + type: integer + timezone: + type: + - string + - "null" + title_count_mode: + type: string + user_id: + type: integer + required: + - user_id + - mailing_list_mode + - mailing_list_mode_frequency + - email_digests + - email_level + - email_messages_level + - external_links_in_new_tab + - color_scheme_id + - dark_scheme_id + - dynamic_favicon + - enable_quoting + - enable_defer + - digest_after_minutes + - automatically_unpin_topics + - auto_track_topics_after_msecs + - notification_level_when_replying + - new_topic_duration_minutes + - email_previous_replies + - email_in_reply_to + - like_notification_frequency + - include_tl0_in_digests + - theme_ids + - theme_key_seq + - allow_private_messages + - enable_allowed_pm_users + - homepage_id + - hide_profile_and_presence + - text_size + - text_size_seq + - title_count_mode + - timezone + - skip_new_user_tips + type: object + username: + type: string + watched_category_ids: + items: {} + type: array + watched_first_post_category_ids: + items: {} + type: array + watched_tags: + items: {} + type: array + watching_first_post_tags: + items: {} + type: array + required: + - id + - username + - name + - avatar_template + - last_posted_at + - last_seen_at + - created_at + - ignored + - muted + - can_ignore_user + - can_mute_user + - can_send_private_messages + - can_send_private_message_to_user + - trust_level + - moderator + - admin + - title + - badge_count + - custom_fields + - time_read + - recent_time_read + - primary_group_id + - primary_group_name + - flair_group_id + - flair_name + - flair_url + - flair_bg_color + - flair_color + - featured_topic + - staged + - can_edit + - can_edit_username + - can_edit_email + - can_edit_name + - uploaded_avatar_id + - has_title_badges + - pending_count + - profile_view_count + - second_factor_enabled + - can_upload_profile_header + - can_upload_user_card_background + - post_count + - can_be_deleted + - can_delete_all_posts + - locale + - muted_category_ids + - regular_category_ids + - watched_tags + - watching_first_post_tags + - tracked_tags + - muted_tags + - tracked_category_ids + - watched_category_ids + - watched_first_post_category_ids + - system_avatar_upload_id + - system_avatar_template + - muted_usernames + - ignored_usernames + - allowed_pm_usernames + - mailing_list_posts_per_day + - can_change_bio + - can_change_location + - can_change_website + - can_change_tracking_preferences + - user_api_keys + - user_auth_tokens + - user_notification_schedule + - use_logo_small_as_avatar + - featured_user_badge_ids + - invited_by + - groups + - group_users + - user_option + type: object + user_badges: + items: {} + type: array + required: + - user_badges + - user + description: user response + summary: Get a user by external_id + tags: + - Users + "/u/by-external/{provider}/{external_id}.json": + get: + operationId: getUserIdentiyProviderExternalId + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - description: |- + Authentication provider name. Can be found in the provider callback + URL: `/auth/{provider}/callback` + in: path + name: provider + required: true + schema: + type: string + - in: path + name: external_id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + user: + additionalProperties: false + properties: + admin: + type: boolean + allowed_pm_usernames: + items: {} + type: array + avatar_template: + type: string + badge_count: + type: integer + can_be_deleted: + type: boolean + can_change_bio: + type: boolean + can_change_location: + type: boolean + can_change_tracking_preferences: + type: boolean + can_change_website: + type: boolean + can_delete_all_posts: + type: boolean + can_edit: + type: boolean + can_edit_email: + type: boolean + can_edit_name: + type: boolean + can_edit_username: + type: boolean + can_ignore_user: + type: boolean + can_mute_user: + type: boolean + can_send_private_message_to_user: + type: boolean + can_send_private_messages: + type: boolean + can_upload_profile_header: + type: boolean + can_upload_user_card_background: + type: boolean + created_at: + type: string + custom_fields: + additionalProperties: false + properties: + first_name: + type: + - string + - "null" + type: object + featured_topic: + type: + - string + - "null" + featured_user_badge_ids: + items: {} + type: array + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_group_id: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + group_users: + items: + additionalProperties: false + properties: + group_id: + type: integer + notification_level: + type: integer + owner: + type: boolean + user_id: + type: integer + required: + - group_id + - user_id + - notification_level + type: object + type: array + groups: + items: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + display_name: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - display_name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + type: array + has_title_badges: + type: boolean + id: + type: integer + ignored: + type: boolean + ignored_usernames: + items: {} + type: array + invited_by: + type: + - string + - "null" + last_posted_at: + type: + - string + - "null" + last_seen_at: + type: + - string + - "null" + locale: + type: + - string + - "null" + mailing_list_posts_per_day: + type: integer + moderator: + type: boolean + muted: + type: boolean + muted_category_ids: + items: {} + type: array + muted_tags: + items: {} + type: array + muted_usernames: + items: {} + type: array + name: + type: string + pending_count: + type: integer + pending_posts_count: + type: integer + post_count: + type: integer + primary_group_id: + type: + - string + - "null" + primary_group_name: + type: + - string + - "null" + profile_view_count: + type: integer + recent_time_read: + type: integer + regular_category_ids: + items: {} + type: array + second_factor_backup_enabled: + type: boolean + second_factor_enabled: + type: boolean + staged: + type: boolean + system_avatar_template: + type: string + system_avatar_upload_id: + type: + - string + - "null" + time_read: + type: integer + title: + type: + - string + - "null" + tracked_category_ids: + items: {} + type: array + tracked_tags: + items: {} + type: array + trust_level: + type: integer + uploaded_avatar_id: + type: + - string + - "null" + use_logo_small_as_avatar: + type: boolean + user_api_keys: + type: + - string + - "null" + user_auth_tokens: + items: + additionalProperties: false + properties: + browser: + type: string + client_ip: + type: string + created_at: + type: string + device: + type: string + icon: + type: string + id: + type: integer + is_active: + type: boolean + location: + type: string + os: + type: string + seen_at: + type: string + required: + - id + - client_ip + - location + - browser + - device + - os + - icon + - created_at + - seen_at + - is_active + type: object + type: array + user_fields: + additionalProperties: false + properties: + "1": + type: + - string + - "null" + "2": + type: + - string + - "null" + required: + - "1" + - "2" + type: object + user_notification_schedule: + additionalProperties: false + properties: + day_0_end_time: + type: integer + day_0_start_time: + type: integer + day_1_end_time: + type: integer + day_1_start_time: + type: integer + day_2_end_time: + type: integer + day_2_start_time: + type: integer + day_3_end_time: + type: integer + day_3_start_time: + type: integer + day_4_end_time: + type: integer + day_4_start_time: + type: integer + day_5_end_time: + type: integer + day_5_start_time: + type: integer + day_6_end_time: + type: integer + day_6_start_time: + type: integer + enabled: + type: boolean + required: + - enabled + - day_0_start_time + - day_0_end_time + - day_1_start_time + - day_1_end_time + - day_2_start_time + - day_2_end_time + - day_3_start_time + - day_3_end_time + - day_4_start_time + - day_4_end_time + - day_5_start_time + - day_5_end_time + - day_6_start_time + - day_6_end_time + type: object + user_option: + additionalProperties: false + properties: + allow_private_messages: + type: boolean + auto_track_topics_after_msecs: + type: integer + automatically_unpin_topics: + type: boolean + bookmark_auto_delete_preference: + type: integer + color_scheme_id: + type: + - string + - "null" + dark_scheme_id: + type: + - string + - "null" + default_calendar: + type: string + digest_after_minutes: + type: integer + dynamic_favicon: + type: boolean + email_digests: + type: boolean + email_in_reply_to: + type: boolean + email_level: + type: integer + email_messages_level: + type: integer + email_previous_replies: + type: integer + enable_allowed_pm_users: + type: boolean + enable_defer: + type: boolean + enable_quoting: + type: boolean + external_links_in_new_tab: + type: boolean + hide_profile_and_presence: + type: boolean + homepage_id: + type: + - string + - "null" + include_tl0_in_digests: + type: boolean + like_notification_frequency: + type: integer + mailing_list_mode: + type: boolean + mailing_list_mode_frequency: + type: integer + new_topic_duration_minutes: + type: integer + notification_level_when_replying: + type: integer + oldest_search_log_date: + type: + - string + - "null" + seen_popups: + type: + - array + - "null" + sidebar_list_destination: + type: string + skip_new_user_tips: + type: boolean + text_size: + type: string + text_size_seq: + type: integer + theme_ids: + items: {} + type: array + theme_key_seq: + type: integer + timezone: + type: + - string + - "null" + title_count_mode: + type: string + user_id: + type: integer + required: + - user_id + - mailing_list_mode + - mailing_list_mode_frequency + - email_digests + - email_level + - email_messages_level + - external_links_in_new_tab + - color_scheme_id + - dark_scheme_id + - dynamic_favicon + - enable_quoting + - enable_defer + - digest_after_minutes + - automatically_unpin_topics + - auto_track_topics_after_msecs + - notification_level_when_replying + - new_topic_duration_minutes + - email_previous_replies + - email_in_reply_to + - like_notification_frequency + - include_tl0_in_digests + - theme_ids + - theme_key_seq + - allow_private_messages + - enable_allowed_pm_users + - homepage_id + - hide_profile_and_presence + - text_size + - text_size_seq + - title_count_mode + - timezone + - skip_new_user_tips + type: object + username: + type: string + watched_category_ids: + items: {} + type: array + watched_first_post_category_ids: + items: {} + type: array + watched_tags: + items: {} + type: array + watching_first_post_tags: + items: {} + type: array + required: + - id + - username + - name + - avatar_template + - last_posted_at + - last_seen_at + - created_at + - ignored + - muted + - can_ignore_user + - can_mute_user + - can_send_private_messages + - can_send_private_message_to_user + - trust_level + - moderator + - admin + - title + - badge_count + - custom_fields + - time_read + - recent_time_read + - primary_group_id + - primary_group_name + - flair_group_id + - flair_name + - flair_url + - flair_bg_color + - flair_color + - featured_topic + - staged + - can_edit + - can_edit_username + - can_edit_email + - can_edit_name + - uploaded_avatar_id + - has_title_badges + - pending_count + - profile_view_count + - second_factor_enabled + - can_upload_profile_header + - can_upload_user_card_background + - post_count + - can_be_deleted + - can_delete_all_posts + - locale + - muted_category_ids + - regular_category_ids + - watched_tags + - watching_first_post_tags + - tracked_tags + - muted_tags + - tracked_category_ids + - watched_category_ids + - watched_first_post_category_ids + - system_avatar_upload_id + - system_avatar_template + - muted_usernames + - ignored_usernames + - allowed_pm_usernames + - mailing_list_posts_per_day + - can_change_bio + - can_change_location + - can_change_website + - can_change_tracking_preferences + - user_api_keys + - user_auth_tokens + - user_notification_schedule + - use_logo_small_as_avatar + - featured_user_badge_ids + - invited_by + - groups + - group_users + - user_option + type: object + user_badges: + items: {} + type: array + required: + - user_badges + - user + description: user response + summary: Get a user by identity provider external ID + tags: + - Users + "/u/{username}.json": + get: + operationId: getUser + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + user: + additionalProperties: false + properties: + admin: + type: boolean + allowed_pm_usernames: + items: {} + type: array + avatar_template: + type: string + badge_count: + type: integer + can_be_deleted: + type: boolean + can_change_bio: + type: boolean + can_change_location: + type: boolean + can_change_tracking_preferences: + type: boolean + can_change_website: + type: boolean + can_delete_all_posts: + type: boolean + can_edit: + type: boolean + can_edit_email: + type: boolean + can_edit_name: + type: boolean + can_edit_username: + type: boolean + can_ignore_user: + type: boolean + can_mute_user: + type: boolean + can_send_private_message_to_user: + type: boolean + can_send_private_messages: + type: boolean + can_upload_profile_header: + type: boolean + can_upload_user_card_background: + type: boolean + created_at: + type: string + custom_fields: + additionalProperties: false + properties: + first_name: + type: + - string + - "null" + type: object + featured_topic: + type: + - string + - "null" + featured_user_badge_ids: + items: {} + type: array + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_group_id: + type: + - string + - "null" + flair_name: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + group_users: + items: + additionalProperties: false + properties: + group_id: + type: integer + notification_level: + type: integer + owner: + type: boolean + user_id: + type: integer + required: + - group_id + - user_id + - notification_level + type: object + type: array + groups: + items: + additionalProperties: false + properties: + allow_membership_requests: + type: boolean + automatic: + type: boolean + bio_cooked: + type: + - string + - "null" + bio_excerpt: + type: + - string + - "null" + bio_raw: + type: + - string + - "null" + can_admin_group: + type: boolean + can_see_members: + type: boolean + default_notification_level: + type: integer + display_name: + type: string + flair_bg_color: + type: + - string + - "null" + flair_color: + type: + - string + - "null" + flair_url: + type: + - string + - "null" + full_name: + type: + - string + - "null" + grant_trust_level: + type: + - string + - "null" + has_messages: + type: boolean + id: + type: integer + incoming_email: + type: + - string + - "null" + members_visibility_level: + type: integer + membership_request_template: + type: + - string + - "null" + mentionable_level: + type: integer + messageable_level: + type: integer + name: + type: string + primary_group: + type: boolean + public_admission: + type: boolean + public_exit: + type: boolean + publish_read_state: + type: boolean + title: + type: + - string + - "null" + user_count: + type: integer + visibility_level: + type: integer + required: + - id + - automatic + - name + - display_name + - user_count + - mentionable_level + - messageable_level + - visibility_level + - primary_group + - title + - grant_trust_level + - incoming_email + - has_messages + - flair_url + - flair_bg_color + - flair_color + - bio_raw + - bio_cooked + - bio_excerpt + - public_admission + - public_exit + - allow_membership_requests + - full_name + - default_notification_level + - membership_request_template + - members_visibility_level + - can_see_members + - can_admin_group + - publish_read_state + type: object + type: array + has_title_badges: + type: boolean + id: + type: integer + ignored: + type: boolean + ignored_usernames: + items: {} + type: array + invited_by: + type: + - string + - "null" + last_posted_at: + type: + - string + - "null" + last_seen_at: + type: + - string + - "null" + locale: + type: + - string + - "null" + mailing_list_posts_per_day: + type: integer + moderator: + type: boolean + muted: + type: boolean + muted_category_ids: + items: {} + type: array + muted_tags: + items: {} + type: array + muted_usernames: + items: {} + type: array + name: + type: string + pending_count: + type: integer + pending_posts_count: + type: integer + post_count: + type: integer + primary_group_id: + type: + - string + - "null" + primary_group_name: + type: + - string + - "null" + profile_view_count: + type: integer + recent_time_read: + type: integer + regular_category_ids: + items: {} + type: array + second_factor_backup_enabled: + type: boolean + second_factor_enabled: + type: boolean + staged: + type: boolean + system_avatar_template: + type: string + system_avatar_upload_id: + type: + - string + - "null" + time_read: + type: integer + title: + type: + - string + - "null" + tracked_category_ids: + items: {} + type: array + tracked_tags: + items: {} + type: array + trust_level: + type: integer + uploaded_avatar_id: + type: + - string + - "null" + use_logo_small_as_avatar: + type: boolean + user_api_keys: + type: + - string + - "null" + user_auth_tokens: + items: + additionalProperties: false + properties: + browser: + type: string + client_ip: + type: string + created_at: + type: string + device: + type: string + icon: + type: string + id: + type: integer + is_active: + type: boolean + location: + type: string + os: + type: string + seen_at: + type: string + required: + - id + - client_ip + - location + - browser + - device + - os + - icon + - created_at + - seen_at + - is_active + type: object + type: array + user_fields: + additionalProperties: false + properties: + "1": + type: + - string + - "null" + "2": + type: + - string + - "null" + required: + - "1" + - "2" + type: object + user_notification_schedule: + additionalProperties: false + properties: + day_0_end_time: + type: integer + day_0_start_time: + type: integer + day_1_end_time: + type: integer + day_1_start_time: + type: integer + day_2_end_time: + type: integer + day_2_start_time: + type: integer + day_3_end_time: + type: integer + day_3_start_time: + type: integer + day_4_end_time: + type: integer + day_4_start_time: + type: integer + day_5_end_time: + type: integer + day_5_start_time: + type: integer + day_6_end_time: + type: integer + day_6_start_time: + type: integer + enabled: + type: boolean + required: + - enabled + - day_0_start_time + - day_0_end_time + - day_1_start_time + - day_1_end_time + - day_2_start_time + - day_2_end_time + - day_3_start_time + - day_3_end_time + - day_4_start_time + - day_4_end_time + - day_5_start_time + - day_5_end_time + - day_6_start_time + - day_6_end_time + type: object + user_option: + additionalProperties: false + properties: + allow_private_messages: + type: boolean + auto_track_topics_after_msecs: + type: integer + automatically_unpin_topics: + type: boolean + bookmark_auto_delete_preference: + type: integer + color_scheme_id: + type: + - string + - "null" + dark_scheme_id: + type: + - string + - "null" + default_calendar: + type: string + digest_after_minutes: + type: integer + dynamic_favicon: + type: boolean + email_digests: + type: boolean + email_in_reply_to: + type: boolean + email_level: + type: integer + email_messages_level: + type: integer + email_previous_replies: + type: integer + enable_allowed_pm_users: + type: boolean + enable_defer: + type: boolean + enable_quoting: + type: boolean + external_links_in_new_tab: + type: boolean + hide_profile_and_presence: + type: boolean + homepage_id: + type: + - string + - "null" + include_tl0_in_digests: + type: boolean + like_notification_frequency: + type: integer + mailing_list_mode: + type: boolean + mailing_list_mode_frequency: + type: integer + new_topic_duration_minutes: + type: integer + notification_level_when_replying: + type: integer + oldest_search_log_date: + type: + - string + - "null" + seen_popups: + type: + - array + - "null" + sidebar_list_destination: + type: string + skip_new_user_tips: + type: boolean + text_size: + type: string + text_size_seq: + type: integer + theme_ids: + items: {} + type: array + theme_key_seq: + type: integer + timezone: + type: + - string + - "null" + title_count_mode: + type: string + user_id: + type: integer + required: + - user_id + - mailing_list_mode + - mailing_list_mode_frequency + - email_digests + - email_level + - email_messages_level + - external_links_in_new_tab + - color_scheme_id + - dark_scheme_id + - dynamic_favicon + - enable_quoting + - enable_defer + - digest_after_minutes + - automatically_unpin_topics + - auto_track_topics_after_msecs + - notification_level_when_replying + - new_topic_duration_minutes + - email_previous_replies + - email_in_reply_to + - like_notification_frequency + - include_tl0_in_digests + - theme_ids + - theme_key_seq + - allow_private_messages + - enable_allowed_pm_users + - homepage_id + - hide_profile_and_presence + - text_size + - text_size_seq + - title_count_mode + - timezone + - skip_new_user_tips + type: object + username: + type: string + watched_category_ids: + items: {} + type: array + watched_first_post_category_ids: + items: {} + type: array + watched_tags: + items: {} + type: array + watching_first_post_tags: + items: {} + type: array + required: + - id + - username + - name + - avatar_template + - last_posted_at + - last_seen_at + - created_at + - ignored + - muted + - can_ignore_user + - can_mute_user + - can_send_private_messages + - can_send_private_message_to_user + - trust_level + - moderator + - admin + - title + - badge_count + - custom_fields + - time_read + - recent_time_read + - primary_group_id + - primary_group_name + - flair_group_id + - flair_name + - flair_url + - flair_bg_color + - flair_color + - featured_topic + - staged + - can_edit + - can_edit_username + - can_edit_email + - can_edit_name + - uploaded_avatar_id + - has_title_badges + - pending_count + - profile_view_count + - second_factor_enabled + - can_upload_profile_header + - can_upload_user_card_background + - post_count + - can_be_deleted + - can_delete_all_posts + - locale + - muted_category_ids + - regular_category_ids + - watched_tags + - watching_first_post_tags + - tracked_tags + - muted_tags + - tracked_category_ids + - watched_category_ids + - watched_first_post_category_ids + - system_avatar_upload_id + - system_avatar_template + - muted_usernames + - ignored_usernames + - allowed_pm_usernames + - mailing_list_posts_per_day + - can_change_bio + - can_change_location + - can_change_website + - can_change_tracking_preferences + - user_api_keys + - user_auth_tokens + - user_notification_schedule + - use_logo_small_as_avatar + - featured_user_badge_ids + - invited_by + - groups + - group_users + - user_option + type: object + user_badges: + items: {} + type: array + required: + - user_badges + - user + description: user response + summary: Get a single user by username + tags: + - Users + put: + operationId: updateUser + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + - in: path + name: username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + email: + type: string + external_ids: + type: object + name: + type: string + password: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + type: string + user: + type: object + required: + - success + - user + description: user updated + summary: Update a user + tags: + - Users + "/u/{username}/emails.json": + get: + operationId: getUserEmails + parameters: + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + associated_accounts: + items: {} + type: array + email: + type: string + secondary_emails: + items: {} + type: array + unconfirmed_emails: + items: {} + type: array + required: + - email + - secondary_emails + - unconfirmed_emails + - associated_accounts + description: success response + summary: Get email addresses belonging to a user + tags: + - Users + "/u/{username}/preferences/avatar/pick.json": + put: + operationId: updateAvatar + parameters: + - in: path + name: username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + type: + enum: + - uploaded + - custom + - gravatar + - system + type: string + upload_id: + type: integer + required: + - upload_id + - type + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + examples: + - OK + type: string + required: + - success + description: avatar updated + summary: Update avatar + tags: + - Users + "/u/{username}/preferences/email.json": + put: + operationId: updateEmail + parameters: + - in: path + name: username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + email: + format: email + type: string + required: + - email + responses: + "200": + description: email updated + summary: Update email + tags: + - Users + "/u/{username}/preferences/username.json": + put: + operationId: updateUsername + parameters: + - in: path + name: username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + new_username: + type: string + required: + - new_username + responses: + "200": + description: username updated + summary: Update username + tags: + - Users + /uploads.json: + post: + operationId: createUpload + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + additionalProperties: false + properties: + file: {} + synchronous: + description: Use this flag to return an id and url + type: boolean + type: + enum: + - avatar + - profile_background + - card_background + - custom_emoji + - composer + type: string + user_id: + description: required if uploading an avatar + type: integer + required: + - type + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + dominant_color: + type: + - string + - "null" + extension: + type: string + filesize: + type: integer + height: + type: integer + human_filesize: + type: string + id: + type: integer + original_filename: + type: string + retain_hours: + type: + - string + - "null" + short_path: + type: string + short_url: + type: string + thumbnail_height: + type: integer + thumbnail_width: + type: integer + url: + type: string + width: + type: integer + required: + - id + - url + - original_filename + - filesize + - width + - height + - thumbnail_width + - thumbnail_height + - extension + - short_url + - short_path + - retain_hours + - human_filesize + description: file uploaded + summary: Creates an upload + tags: + - Uploads + /uploads/abort-multipart.json: + post: + description: |+ + This endpoint aborts the multipart upload initiated with /create-multipart. + This should be used when cancelling the upload. It does not matter if parts + were already uploaded into the external storage provider. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: abortMultipart + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + external_upload_identifier: + description: |- + The identifier of the multipart upload in the external + storage provider. This is the multipart upload_id in AWS S3. + examples: + - 84x83tmxy398t3y._Q_z8CoJYVr69bE6D7f8J6Oo0434QquLFoYdGVerWFx9X5HDEI_TP_95c34n853495x35345394.d.ghQ + type: string + required: + - external_upload_identifier + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + success: + examples: + - OK + type: string + required: + - success + description: external upload initialized + summary: Abort multipart upload + tags: + - Uploads + /uploads/batch-presign-multipart-parts.json: + post: + description: |+ + Multipart uploads are uploaded in chunks or parts to individual presigned + URLs, similar to the one generated by /generate-presigned-put. The part + numbers provided must be between 1 and 10000. The total number of parts + will depend on the chunk size in bytes that you intend to use to upload + each chunk. For example a 12MB file may have 2 5MB chunks and a final + 2MB chunk, for part numbers 1, 2, and 3. + + This endpoint will return a presigned URL for each part number provided, + which you can then use to send PUT requests for the binary chunk corresponding + to that part. When the part is uploaded, the provider should return an + ETag for the part, and this should be stored along with the part number, + because this is needed to complete the multipart upload. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: batchPresignMultipartParts + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + part_numbers: + description: |- + The part numbers to generate the presigned URLs for, + must be between 1 and 10000. + examples: + - - 1 + - 2 + - 3 + type: array + unique_identifier: + description: |- + The unique identifier returned in the original /create-multipart + request. + examples: + - 66e86218-80d9-4bda-b4d5-2b6def968705 + type: string + required: + - part_numbers + - unique_identifier + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + presigned_urls: + description: |- + The presigned URLs for each part number, which has + the part numbers as keys. + examples: + - "1": https://discourse-martin-uploads-test.s3.us-east-2.amazonaws.com/temp/uploads/default/123abc/123abc.jpg?partNumber=1&uploadId=123456abcd&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=test&X-Amz-Date=20211222T012336Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=abc123 + type: object + required: + - presigned_urls + description: external upload initialized + summary: Generates batches of presigned URLs for multipart parts + tags: + - Uploads + /uploads/complete-external-upload.json: + post: + description: |+ + Completes an external upload initialized with /get-presigned-put. The + file will be moved from its temporary location in external storage to + a final destination in the S3 bucket. An Upload record will also be + created in the database in most cases. + + If a sha1-checksum was provided in the initial request it will also + be compared with the uploaded file in storage to make sure the same + file was uploaded. The file size will be compared for the same reason. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: completeExternalUpload + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + for_private_message: + description: |- + Optionally set this to true if the upload is for a + private message. + examples: + - "true" + type: string + for_site_setting: + description: |- + Optionally set this to true if the upload is for a + site setting. + examples: + - "true" + type: string + pasted: + description: |- + Optionally set this to true if the upload was pasted + into the upload area. This will convert PNG files to JPEG. + examples: + - "true" + type: string + unique_identifier: + description: |- + The unique identifier returned in the original /generate-presigned-put + request. + examples: + - 66e86218-80d9-4bda-b4d5-2b6def968705 + type: string + required: + - unique_identifier + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + dominant_color: + type: + - string + - "null" + extension: + type: string + filesize: + type: integer + height: + type: integer + human_filesize: + type: string + id: + type: integer + original_filename: + type: string + retain_hours: + type: + - string + - "null" + short_path: + type: string + short_url: + type: string + thumbnail_height: + type: integer + thumbnail_width: + type: integer + url: + type: string + width: + type: integer + required: + - id + - url + - original_filename + - filesize + - width + - height + - thumbnail_width + - thumbnail_height + - extension + - short_url + - short_path + - retain_hours + - human_filesize + description: external upload initialized + summary: Completes a direct external upload + tags: + - Uploads + /uploads/complete-multipart.json: + post: + description: |+ + Completes the multipart upload in the external store, and copies the + file from its temporary location to its final location in the store. + All of the parts must have been uploaded to the external storage provider. + An Upload record will be completed in most cases once the file is copied + to its final location. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: completeMultipart + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + parts: + description: |- + All of the part numbers and their corresponding ETags + that have been uploaded must be provided. + examples: + - - etag: 0c376dcfcc2606f4335bbc732de93344 + part_number: 1 + - etag: 09ert8cfcc2606f4335bbc732de91122 + part_number: 2 + type: array + unique_identifier: + description: |- + The unique identifier returned in the original /create-multipart + request. + examples: + - 66e86218-80d9-4bda-b4d5-2b6def968705 + type: string + required: + - unique_identifier + - parts + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + dominant_color: + type: + - string + - "null" + extension: + type: string + filesize: + type: integer + height: + type: integer + human_filesize: + type: string + id: + type: integer + original_filename: + type: string + retain_hours: + type: + - string + - "null" + short_path: + type: string + short_url: + type: string + thumbnail_height: + type: integer + thumbnail_width: + type: integer + url: + type: string + width: + type: integer + required: + - id + - url + - original_filename + - filesize + - width + - height + - thumbnail_width + - thumbnail_height + - extension + - short_url + - short_path + - retain_hours + - human_filesize + description: external upload initialized + summary: Complete multipart upload + tags: + - Uploads + /uploads/create-multipart.json: + post: + description: |+ + Creates a multipart upload in the external storage provider, storing + a temporary reference to the external upload similar to /get-presigned-put. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: createMultipartUpload + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + file_name: + examples: + - IMG_2021.jpeg + type: string + file_size: + description: File size should be represented in bytes. + examples: + - 4096 + type: integer + metadata: + additionalProperties: false + properties: + sha1-checksum: + description: |- + The SHA1 checksum of the upload binary blob. Optionally + be provided and serves as an additional security check when + later processing the file in complete-external-upload endpoint. + type: string + type: object + upload_type: + enum: + - avatar + - profile_background + - card_background + - custom_emoji + - composer + type: string + required: + - upload_type + - file_name + - file_size + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + external_upload_identifier: + description: |- + The identifier of the multipart upload in the external + storage provider. This is the multipart upload_id in AWS S3. + examples: + - 84x83tmxy398t3y._Q_z8CoJYVr69bE6D7f8J6Oo0434QquLFoYdGVerWFx9X5HDEI_TP_95c34n853495x35345394.d.ghQ + type: string + key: + description: |- + The path of the temporary file on the external storage + service. + examples: + - temp/site/uploads/default/12345/67890.jpg + type: string + unique_identifier: + description: |- + A unique string that identifies the external upload. + This must be stored and then sent in the /complete-multipart + and /batch-presign-multipart-parts endpoints. + examples: + - 66e86218-80d9-4bda-b4d5-2b6def968705 + type: string + required: + - external_upload_identifier + - key + - unique_identifier + description: external upload initialized + summary: Creates a multipart external upload + tags: + - Uploads + /uploads/generate-presigned-put.json: + post: + description: |+ + Direct external uploads bypass the usual method of creating uploads + via the POST /uploads route, and upload directly to an external provider, + which by default is S3. This route begins the process, and will return + a unique identifier for the external upload as well as a presigned URL + which is where the file binary blob should be uploaded to. + + Once the upload is complete to the external service, you must call the + POST /complete-external-upload route using the unique identifier returned + by this route, which will create any required Upload record in the Discourse + database and also move file from its temporary location to the final + destination in the external storage service. + + You must have the correct permissions and CORS settings configured in your + external provider. We support AWS S3 as the default. See: + + https://meta.discourse.org/t/-/210469#s3-multipart-direct-uploads-4. + + An external file store must be set up and `enable_direct_s3_uploads` must + be set to true for this endpoint to function. + + operationId: generatePresignedPut + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + file_name: + examples: + - IMG_2021.jpeg + type: string + file_size: + description: File size should be represented in bytes. + examples: + - 4096 + type: integer + metadata: + additionalProperties: false + properties: + sha1-checksum: + description: |- + The SHA1 checksum of the upload binary blob. Optionally + be provided and serves as an additional security check when + later processing the file in complete-external-upload endpoint. + type: string + type: object + type: + enum: + - avatar + - profile_background + - card_background + - custom_emoji + - composer + type: string + required: + - type + - file_name + - file_size + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + key: + description: |- + The path of the temporary file on the external storage + service. + examples: + - temp/site/uploads/default/12345/67890.jpg + type: string + unique_identifier: + description: |- + A unique string that identifies the external upload. + This must be stored and then sent in the /complete-external-upload + endpoint to complete the direct upload. + examples: + - 66e86218-80d9-4bda-b4d5-2b6def968705 + type: string + url: + description: |- + A presigned PUT URL which must be used to upload + the file binary blob to. + examples: + - https://file-uploads.s3.us-west-2.amazonaws.com/temp/site/uploads/default/123/456.jpg?x-amz-acl=private&x-amz-meta-sha1-checksum=sha1&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AAAAus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20211221T011246Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=12345678 + type: string + description: external upload initialized + summary: Initiates a direct external upload + tags: + - Uploads + "/user-badges/{username}.json": + get: + operationId: listUserBadges + parameters: + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + badge_types: + items: + additionalProperties: false + properties: + id: + type: integer + name: + type: string + sort_order: + type: integer + required: + - id + - name + - sort_order + type: object + type: array + badges: + items: + additionalProperties: false + properties: + allow_title: + type: boolean + badge_grouping_id: + type: integer + badge_type_id: + type: integer + description: + type: string + enabled: + type: boolean + grant_count: + type: integer + icon: + type: string + id: + type: integer + image_url: + type: + - string + - "null" + listable: + type: boolean + manually_grantable: + type: boolean + multiple_grant: + type: boolean + name: + type: string + slug: + type: string + system: + type: boolean + required: + - id + - name + - description + - grant_count + - allow_title + - multiple_grant + - icon + - image_url + - listable + - enabled + - badge_grouping_id + - system + - slug + - manually_grantable + - badge_type_id + type: object + type: array + granted_bies: + items: + additionalProperties: false + properties: + admin: + type: boolean + avatar_template: + type: string + flair_name: + type: + - string + - "null" + id: + type: integer + moderator: + type: boolean + name: + type: string + trust_level: + type: integer + username: + type: string + required: + - id + - username + - name + - avatar_template + - flair_name + - admin + - moderator + - trust_level + type: object + type: array + user_badges: + items: + additionalProperties: false + properties: + badge_id: + type: integer + can_favorite: + type: boolean + granted_at: + type: string + granted_by_id: + type: integer + grouping_position: + type: integer + id: + type: integer + is_favorite: + type: + - string + - "null" + required: + - id + - granted_at + - grouping_position + - is_favorite + - can_favorite + - badge_id + - granted_by_id + type: object + type: array + required: + - user_badges + description: success response + summary: List badges for a user + tags: + - Badges + - Users + /user_actions.json: + get: + operationId: listUserActions + parameters: + - in: query + name: offset + required: true + schema: + type: integer + - in: query + name: username + required: true + schema: + type: string + - in: query + name: filter + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + user_actions: + items: + additionalProperties: false + properties: + acting_avatar_template: + type: string + acting_name: + type: + - string + - "null" + acting_user_id: + type: integer + acting_username: + type: string + action_code: + type: + - string + - "null" + action_type: + type: integer + archived: + type: boolean + avatar_template: + type: string + category_id: + type: integer + closed: + type: boolean + created_at: + type: string + deleted: + type: boolean + excerpt: + type: string + hidden: + type: + - string + - "null" + name: + type: + - string + - "null" + post_id: + type: + - string + - "null" + post_number: + type: integer + post_type: + type: + - string + - "null" + slug: + type: string + target_name: + type: + - string + - "null" + target_user_id: + type: integer + target_username: + type: string + title: + type: string + topic_id: + type: integer + user_id: + type: integer + username: + type: string + required: + - excerpt + - action_type + - created_at + - avatar_template + - acting_avatar_template + - slug + - topic_id + - target_user_id + - target_name + - target_username + - post_number + - post_id + - username + - name + - user_id + - acting_username + - acting_name + - acting_user_id + - title + - deleted + - hidden + - post_type + - action_code + - category_id + - closed + - archived + type: object + type: array + required: + - user_actions + description: response + summary: Get a list of user actions + tags: + - Users + "/user_avatar/{username}/refresh_gravatar.json": + post: + operationId: refreshGravatar + parameters: + - in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + gravatar_avatar_template: + type: + - string + - "null" + gravatar_upload_id: + type: + - integer + - "null" + required: + - gravatar_upload_id + - gravatar_avatar_template + description: response + summary: Refresh gravatar + tags: + - Users + - Admin + /users.json: + post: + operationId: createUser + parameters: + - in: header + name: Api-Key + required: true + schema: + type: string + - in: header + name: Api-Username + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + active: + description: |- + This param requires an api key in the request header + or it will be ignored + type: boolean + approved: + type: boolean + email: + type: string + external_ids: + type: object + name: + type: string + password: + type: string + "user_fields[1]": + type: boolean + username: + type: string + required: + - name + - email + - password + - username + responses: + "200": + content: + application/json: + schema: + additionalProperties: false + properties: + active: + type: boolean + message: + type: string + success: + type: boolean + user_id: + type: integer + required: + - success + - active + - message + description: user created + summary: Creates a user + tags: + - Users + "/users/password-reset/{token}.json": + put: + operationId: changePassword + parameters: + - in: path + name: token + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + password: + type: string + username: + type: string + required: + - username + - password + responses: + "200": + description: success response + summary: Change password + tags: + - Users +components: + schemas: {} diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/listennotes.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/listennotes.yaml new file mode 100644 index 000000000..90ffa6300 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/listennotes.yaml @@ -0,0 +1,3249 @@ +openapi: 3.1.0 +servers: + - description: API Production Server + url: https://listen-api.listennotes.com/api/v2 +info: + contact: + email: hello@listennotes.com + name: Listen Notes + url: https://www.listennotes.com/api/ + x-twitter: listennotes + description: | + Simple & no-nonsense podcast search & directory API. Search all podcasts and episodes by people, places, or topics. + termsOfService: https://www.listennotes.com/api/terms/ + title: "Listen API: Podcast Search, Directory, and Insights API" + version: "2.0" + x-apisguru-categories: + - entertainment + x-logo: + url: https://twitter.com/listennotes/profile_image?size=original + x-origin: + - converter: + url: https://github.com/mermade/oas-kit + version: 7.0.4 + format: openapi + url: https://listen-api.listennotes.com/api/v2/openapi.yaml + version: "3.1" + x-providerName: listennotes.com +tags: + - description: Endpoints to search podcasts + name: Search API + - description: Endpoints to fetch podcasts data + name: Directory API + - description: Endpoints to fetch Listen Later playlists data + name: Playlist API + - description: Endpoints to improve the podcast database + name: Podcaster API + - description: Endpoints to get insights of podcasts, e.g., audience demographics + name: Insights API +paths: + /best_podcasts: + get: + description: | + Get a list of curated best podcasts by genre, + which are curated by Listen Notes staffs based on various signals from the Internet, e.g., + top charts on other podcast platforms, recommendations from mainstream media, + user activities on listennotes.com... + You can get the genre ids from `GET /genres` endpoint. + This endpoint returns same data as https://www.listennotes.com/best-podcasts/ + operationId: getBestPodcasts + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - $ref: "#/components/parameters/genreIdParam" + - description: Page number of those podcasts in this genre. + in: query + name: page + required: false + schema: + examples: + - 2 + type: integer + - description: | + Filter best podcasts by country/region. + Please note that podcasts that are "best" in a country/region may not be produced in that country/region. + For example, a podcast from the US may be very popular in Canada. + You can get the supported country codes (e.g., us, jp, gb...) from `GET /regions`. + If not specified, you'll get "best podcasts" in United States. + in: query + name: region + required: false + schema: + default: us + examples: + - us + type: string + - description: | + Filter best podcasts by the publisher's country/region. + This is to narrow down the results to include "best podcasts" produced in a specific country/region. + You can get the supported country codes (e.g., us, jp, gb...) from `GET /regions`. + If not specified, you'll get "best podcasts" produced in any country/region. + If you want to get a country/region's "best podcasts" that are also produced in that country/region, + then you need to specify both **region** and **publisher_region**, + e.g., `region=jp` and `publisher_region=jp`. + in: query + name: publisher_region + required: false + schema: + type: string + - description: | + Filter best podcasts by language. + You can get a list of supported languages (e.g., English, Chinese, Japanese...) from `GET /languages`. + If not specified, you'll get "best podcasts" in any language. + in: query + name: language + required: false + schema: + type: string + - description: | + How do you want to sort these podcasts? + If you'd like to sort by popularity, please use **listen_score**. + example: listen_score + explode: true + in: query + name: sort + required: false + schema: + default: recent_added_first + enum: + - recent_added_first + - oldest_added_first + - recent_published_first + - oldest_published_first + - listen_score + type: string + style: form + - $ref: "#/components/parameters/safeModeParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/BestPodcastsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through podcasts. + operationId: getBestPodcasts + parameters: + page: $response.body#/next_page_number + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a list of best podcasts by genre + tags: + - Directory API + /curated_podcasts: + get: + description: | + A bunch of curated lists from online media. For each list, you'll get basic info of up to 5 podcasts. To get detailed meta data of all podcasts in a specific list, you need to use `GET /curated_podcasts/{id}`. We add new curated lists to the database on a daily basis. + operationId: getCuratedPodcasts + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Page number of curated lists. + example: 2 + explode: true + in: query + name: page + required: false + schema: + default: 1 + type: integer + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetCuratedPodcastsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through curated lists. + operationId: getCuratedPodcasts + parameters: + page: $response.body#/next_page_number + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch curated lists of podcasts + tags: + - Directory API + "/curated_podcasts/{id}": + get: + description: | + Get detailed meta data of all podcasts in a specific curated list. + This endpoint returns same data as https://www.listennotes.com/curated-podcasts/ + operationId: getCuratedPodcastById + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + id for a specific curated list of podcasts. You can get the id from the response of `GET /search?type=curated` or `GET /curated_podcasts`. + explode: false + in: path + name: id + required: true + schema: + examples: + - SDFKduyJ47r + type: string + style: simple + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CuratedListFull" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a curated list of podcasts by id + tags: + - Directory API + /episodes: + post: + description: | + Batch fetch basic meta data for up to 10 episodes. This endpoint could be used to implement custom playlists for individual episodes. For detailed meta data of an individual episode, you need to use `GET /episodes/{id}`. This endpoint is available only in the PRO/ENTERPRISE plan. + operationId: getEpisodesInBatch + parameters: + - $ref: "#/components/parameters/apiKeyParam" + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/GetEpisodesInBatchForm" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetEpisodesInBatchResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Batch fetch basic meta data for episodes + tags: + - Directory API + "/episodes/{id}": + get: + description: Fetch detailed meta data for a specific episode. + operationId: getEpisodeById + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: id for a specific episode. You can get episode id from using other endpoints, e.g., `GET /search`... + explode: false + in: path + name: id + required: true + schema: + examples: + - 6b6d65930c5a4f71b254465871fed370 + type: string + style: simple + - description: To include the transcript of this episode or not? If it is 1, then include the transcript in the **transcript** field. The default value is 0 - we don't include transcript by default, because 1) it would make the response data very big, thus slow response time; 2) less than 1% of episodes have transcripts. The transcript field is available only in the PRO/ENTERPRISE plan. + explode: false + in: query + name: show_transcript + required: false + schema: + default: 0 + examples: + - 1 + type: integer + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EpisodeFull" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch detailed meta data for an episode by id + tags: + - Directory API + "/episodes/{id}/recommendations": + get: + description: Fetch up to 8 episode recommendations based on the given episode id. + operationId: getEpisodeRecommendations + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Episode id. + example: 254444fa6cf64a43a95292a70eb6869b + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + - $ref: "#/components/parameters/safeModeParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetEpisodeRecommendationsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch recommendations for an episode + tags: + - Directory API + /genres: + get: + description: | + Get a list of podcast genres that are supported in Listen Notes. + The genre id can be passed to other endpoints as a parameter to get podcasts in a specific genre, + e.g., `GET /best_podcasts`, `GET /search`... + You may want to cache the list of genres on the client side. + operationId: getGenres + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + Just show top level genres? If 1, yes, just show top level genres. If 0, no, show all genres. + explode: true + in: query + name: top_level_only + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 1 + type: integer + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetGenresResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a list of podcast genres + tags: + - Directory API + /just_listen: + get: + description: Recently published episodes are more likely to be fetched. Good luck! + operationId: justListen + parameters: + - $ref: "#/components/parameters/apiKeyParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EpisodeSimple" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a random podcast episode + tags: + - Directory API + /languages: + get: + description: | + Get a list of languages that are supported in Listen Notes database. You can use the language string as query parameter in `GET /search`. + operationId: getLanguages + parameters: + - $ref: "#/components/parameters/apiKeyParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetLanguagesResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a list of supported languages for podcasts + tags: + - Directory API + /playlists: + get: + description: | + This endpoint returns same data as listennotes.com/listen under your account. + You can use the **page** parameter to do pagination and fetch more playlists. + operationId: getPlaylists + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + How do you want to sort playlists? + in: query + name: sort + required: false + schema: + default: recent_added_first + enum: + - recent_added_first + - oldest_added_first + - name_a_to_z + - name_z_to_a + examples: + - recent_added_first + type: string + - description: | + Page number of playlists. + in: query + name: page + required: false + schema: + default: 1 + examples: + - 1 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PlaylistsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through playlists. + operationId: getPlaylists + parameters: + page: $response.body#/page + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a list of your playlists. + tags: + - Playlist API + "/playlists/{id}": + get: + description: | + A playlist can be an episode list (i.e., all items are episodes) or a podcast list (i.e., all items are podcasts), + which is essentially the same as those created via listennotes.com/listen/. + This endpoint fetches a list of items (i.e., episodes or podcasts) in the playlist. + You can use the **last_pub_date_ms** parameter to do pagination and fetch more items. + A playlist can be **public** (discoverable on ListenNotes.com), + **unlisted** (accessible to anyone who knows the playlist id), + or **private** (accessible to its owner). + You can fetch all playlists created by you, and **public** / **unlisted** playlists created by others. + operationId: getPlaylistById + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + Playlist id (always 11 characters, e.g., m1pe7z60bsw). + You can get the podcast id from the url of a playlist, e.g., + m1pe7z60bsw is the playlist id of listennotes.com/listen/podcasts-about-podcasting-m1pe7z60bsw + example: m1pe7z60bsw + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + - description: | + The type of this playlist, which should be either **episode_list** or **podcast_list**. + in: query + name: type + required: false + schema: + default: episode_list + enum: + - episode_list + - podcast_list + examples: + - episode_list + type: string + - description: | + For playlist items pagination. + It's the value of **last_timestamp_ms** from the response of last request. + If it's 0 or not specified, just return the latest or the oldest 20 items, + depending on the value of the **sort** parameter. + in: query + name: last_timestamp_ms + required: false + schema: + default: 0 + examples: + - 0 + type: integer + - description: | + How do you want to sort playlist items? + in: query + name: sort + required: false + schema: + default: recent_added_first + enum: + - recent_added_first + - oldest_added_first + - recent_published_first + - oldest_published_first + examples: + - recent_added_first + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PlaylistResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through playlist items. + operationId: getPlaylistById + parameters: + last_timestamp_ms: $response.body#/last_timestamp_ms + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a playlist's info and items (i.e., episodes or podcasts). + tags: + - Playlist API + /podcasts: + post: + description: | + Batch fetch basic meta data for up to 10 podcasts. + This endpoint could be used to build something like OPML import, + allowing users to import a bunch of podcasts via rss urls. + For detailed meta data (including episodes) of an individual podcast, you need to use `GET /podcasts/{id}`. This endpoint is available only in the PRO/ENTERPRISE plan. + operationId: getPodcastsInBatch + parameters: + - $ref: "#/components/parameters/apiKeyParam" + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/GetPodcastsInBatchForm" + required: false + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetPodcastsInBatchResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through latest episodes. + operationId: getPodcastsInBatch + parameters: + next_episode_pub_date: $response.body#/next_episode_pub_date + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Batch fetch basic meta data for podcasts + tags: + - Directory API + "/podcasts/domains/{domain_name}": + get: + description: | + Fetch podcasts by a publisher's domain name, e.g., nytimes.com, wondery.com, npr.org... + Each request will return up to 10 podcasts. You can use the `page` parameter to paginate. + operationId: getPodcastsByDomainName + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: A publisher's domain name, e.g., nytimes.com, wondery.com, npr.org... + example: nytimes.com + explode: false + in: path + name: domain_name + required: true + schema: + type: string + style: simple + - description: Page number of the podcasts from this domain name + in: query + name: page + required: false + schema: + default: 1 + examples: + - 1 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PodcastDomainResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through podcasts. + operationId: getPodcastsByDomainName + parameters: + page: $response.body#/next_page_number + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch podcasts by a publisher's domain name + tags: + - Insights API + /podcasts/submit: + post: + description: | + Podcast hosting services can use this endpoint to help your users directly submit a new podcast to Listen Notes database. If the podcast doesn't exist in the database, "status" in the response will be "in review", and we'll review it within 12 hours. If the podcast exists, "status" in the response will be "found". If this submission is rejected, "status" in the response will be "rejected". You can use `POST /podcasts` to check if multiple podcasts exist in the database. If you want to get a notification once the podcast is accepted, you can either specify the "email" parameter or configure a webhook url in the dashboard: listennotes.com/api/dashboard/#webhooks + operationId: submitPodcast + parameters: + - $ref: "#/components/parameters/apiKeyParam" + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/SubmitPodcastForm" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SubmitPodcastResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Submit a podcast to Listen Notes database + tags: + - Podcaster API + "/podcasts/{id}": + delete: + description: | + Podcast hosting services can use this endpoint to streamline the process of podcast deletion on behave of their users (podcasters). We will review the deletion request within 12 hours. If the podcast is already deleted, the "status" field in the response will be "deleted". Otherwise, the status field will be "in review". If you want to get a notification once the podcast is deleted, you can configure a webhook url in the dashboard: listennotes.com/api/dashboard/#webhooks + operationId: deletePodcastById + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Podcast id. You can get podcast id from using other endpoints, e.g., `GET /search`, `GET /best_podcasts`... + example: 4d3fe717742d4963a85562e9f84d8c79 + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + - description: The reason why this podcast should be deleted, e.g., copyright violation, the podcaster wants to delete it... You can put "testing" here to indicate that you are testing this endpoint, so we will not actually delete the podcast. + example: the podcaster wants to delete it + explode: true + in: query + name: reason + required: false + schema: + type: string + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/DeletePodcastResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Request to delete a podcast + tags: + - Podcaster API + get: + description: | + Fetch detailed meta data and episodes for a specific podcast (up to 10 episodes each time). + You can use the **next_episode_pub_date** parameter to do pagination and fetch more episodes. + operationId: getPodcastById + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Podcast id. You can get podcast id from using other endpoints, e.g., `GET /search`, `GET /best_podcasts`... + example: 4d3fe717742d4963a85562e9f84d8c79 + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + - description: | + For episodes pagination. It's the value of **next_episode_pub_date** from the response of last request. If not specified, just return latest 10 episodes or oldest 10 episodes, depending on the value of the **sort** parameter. + example: 1479154463000 + explode: true + in: query + name: next_episode_pub_date + required: false + schema: + type: integer + style: form + - description: | + How do you want to sort the episodes of this podcast? + example: recent_first + explode: true + in: query + name: sort + required: false + schema: + default: recent_first + enum: + - recent_first + - oldest_first + type: string + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PodcastFull" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through episodes. + operationId: getPodcastById + parameters: + next_episode_pub_date: $response.body#/next_episode_pub_date + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch detailed meta data and episodes for a podcast by id + tags: + - Directory API + "/podcasts/{id}/audience": + get: + description: Fetch audience demographics for a podcast - 1) directly measured on the Listen Notes platform; 2) only supports audience breakdown by regions for now; 3) not every podcast has data. + operationId: getPodcastAudience + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Podcast id. + example: 25212ac3c53240a880dd5032e547047b + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/PodcastAudienceResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch audience demographics for a podcast + tags: + - Insights API + "/podcasts/{id}/recommendations": + get: + description: Fetch up to 8 podcast recommendations based on the given podcast id. + operationId: getPodcastRecommendations + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: Podcast id. + example: 25212ac3c53240a880dd5032e547047b + explode: false + in: path + name: id + required: true + schema: + type: string + style: simple + - $ref: "#/components/parameters/safeModeParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetPodcastRecommendationsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch recommendations for a podcast + tags: + - Directory API + /regions: + get: + description: | + It returns a dictionary of country codes (e.g., us, gb...) & country names (United States, United Kingdom...). The country code is used in the query parameter **region** of `GET /best_podcasts`. + operationId: getRegions + parameters: + - $ref: "#/components/parameters/apiKeyParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GetRegionsResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch a list of supported countries/regions for best podcasts + tags: + - Directory API + /related_searches: + get: + description: Suggest related search terms. The results are more comprehensive than from `GET /typeahead`. This endpoint is available only in the PRO/ENTERPRISE plan. + operationId: getRelatedSearches + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + Search term, e.g., person, place, topic... + explode: true + in: query + name: q + required: true + schema: + examples: + - evergrande + type: string + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/RelatedSearchesResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch related search terms + tags: + - Search API + /search: + get: + description: | + Full-text search on episodes, podcasts, or curated lists of podcasts. + Use the `offset` parameter to paginate through search results. + The FREE plan allows to see up to 30 search results (or `offset` < 30) per query. + The PRO plan allows to see up to 300 search results (or `offset` < 300) per query. + The ENTERPRISE plan allows to see up to 10,000 search results (or `offset` < 10000) per query. + operationId: search + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - $ref: "#/components/parameters/queryParam" + - description: | + Sort by date or not? If 0, then sort by relevance. If 1, then sort by date. + explode: true + in: query + name: sort_by_date + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 0 + type: integer + style: form + - description: | + What type of contents do you want to search for? + explode: true + in: query + name: type + required: false + schema: + default: episode + enum: + - episode + - podcast + - curated + examples: + - episode + type: string + style: form + - description: | + Offset for search results, for pagination. You'll use **next_offset** from response for this parameter. + explode: true + in: query + name: offset + required: false + schema: + default: 0 + examples: + - 0 + type: integer + style: form + - description: | + Minimum audio length in minutes. Applicable only when **type** parameter is **episode** or **podcast**. + If **type** parameter is **episode**, it's for audio length of an episode. + If **type** parameter is **podcast**, it's for average audio length of all episodes in a podcast. + explode: true + in: query + name: len_min + required: false + schema: + default: 0 + examples: + - 10 + type: integer + style: form + - description: | + Maximum audio length in minutes. Applicable only when **type** parameter is **episode** or **podcast**. + If **type** parameter is **episode**, it's for audio length of an episode. + If **type** parameter is **podcast**, it's for average audio length of all episodes in a podcast. + explode: true + in: query + name: len_max + required: false + schema: + examples: + - 30 + type: integer + style: form + - description: | + Minimum number of episodes. Applicable only when type parameter is **podcast**. + explode: true + in: query + name: episode_count_min + required: false + schema: + type: integer + style: form + - description: | + Maximum number of episodes. Applicable only when type parameter is **podcast**. + explode: true + in: query + name: episode_count_max + required: false + schema: + type: integer + style: form + - description: | + Minimum update frequency in hours (how frequently does a podcast release a new episode). For example, if you want to find "weekly" podcasts, then you can set **update_freq_min**=144 hours (or 6 days) and **update_freq_max**=192 hours (or 8 days). Applicable only when type parameter is **podcast**. + explode: true + in: query + name: update_freq_min + required: false + schema: + type: integer + style: form + - description: | + Maximum update frequency in hours (how frequently does a podcast release a new episode). For example, if you want to find "weekly" podcasts, then you can set **update_freq_min**=144 hours (or 6 days) and **update_freq_max**=192 hours (or 8 days). Applicable only when type parameter is **podcast**. + explode: true + in: query + name: update_freq_max + required: false + schema: + type: integer + style: form + - description: | + A comma-delimited string of a list of genre ids. If not specified, then all genres are included. You can find the id and the name of all genres from `GET /genres`. It works only when **type** is *episode* or *podcast*. + explode: true + in: query + name: genre_ids + required: false + schema: + examples: + - 68,82 + type: string + style: form + - description: | + Only show episodes/podcasts/curated lists published before this timestamp (in milliseconds). If **published_before** & **published_after** are used at the same time, **published_before** should be bigger than **published_after**. + explode: true + in: query + name: published_before + required: false + schema: + examples: + - 1580172454000 + type: integer + style: form + - description: | + Only show episodes/podcasts/curated lists published after this timestamp (in milliseconds). If **published_before** & **published_after** are used at the same time, **published_before** should be bigger than **published_after**. + explode: true + in: query + name: published_after + required: false + schema: + default: 0 + examples: + - 0 + type: integer + style: form + - description: | + A comma-delimited string to search only in specific fields. Allowed values are title, description, author, and audio. If not specified, then search every fields. + explode: true + in: query + name: only_in + required: false + schema: + default: title,description,author,audio + examples: + - title,description + type: string + style: form + - description: | + Limit search results to a specific language. If not specified, it'll be any language. You can get a list of supported languages from `GET /languages`. It works only when **type** is *episode* or *podcast*. + explode: true + in: query + name: language + required: false + schema: + examples: + - English + type: string + style: form + - description: | + Limit search results to a specific region (e.g., us, gb, in...). If not specified, it'll be any region. You can get the supported country codes from `GET /regions`. It works only when **type** is *episode* or *podcast*. + in: query + name: region + required: false + schema: + examples: + - "" + type: string + - description: | + A comma-delimited string of podcast ids (up to 5 podcasts) - you can get a podcast id from the **podcast_id** field in response. This parameter is to limit search results from only a few specific podcasts. It works only when **type** is *episode*. + explode: true + in: query + name: ocid + required: false + schema: + type: string + style: form + - description: | + A comma-delimited string of podcast ids (up to 5 podcasts) - you can get a podcast id from the **podcast_id** field in response. This parameter is to exclude search results of a few specific podcasts. It works only when **type** is *episode*. + explode: true + in: query + name: ncid + required: false + schema: + type: string + style: form + - description: | + Whether or not to exclude podcasts/episodes with explicit language. 1 is yes and 0 is no. It works only when **type** is *episode* or *podcast*. + explode: true + in: query + name: safe_mode + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 0 + type: integer + style: form + - description: | + Whether or not to keep only one episode per podcast in search results. 1 is yes and 0 is no. It works only when **type** is *episode*. + explode: true + in: query + name: unique_podcasts + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 0 + type: integer + style: form + - description: | + The maximum number of search results per page. A valid value should be an integer between 1 and 10 (inclusive). + explode: true + in: query + name: page_size + required: false + schema: + default: 10 + examples: + - 10 + type: integer + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SearchResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + links: + paginate: + description: Pagination through search results. + operationId: search + parameters: + offset: $response.body#/next_offset + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Full-text search + tags: + - Search API + /spellcheck: + get: + description: Suggest a list of words that correct the spelling errors of a search term. This endpoint is available only in the PRO/ENTERPRISE plan. + operationId: spellcheck + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - description: | + Search term, e.g., person, place, topic... + explode: true + in: query + name: q + required: true + schema: + examples: + - evergrand stok + type: string + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/SpellCheckResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Spell check on a search term + tags: + - Search API + /trending_searches: + get: + description: Fetch up to 10 most recent trending search terms on the Listen Notes platform. + operationId: getTrendingSearches + parameters: + - $ref: "#/components/parameters/apiKeyParam" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TrendingSearchesResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Fetch trending search terms + tags: + - Search API + /typeahead: + get: + description: Suggest search terms, podcast genres, and podcasts. + operationId: typeahead + parameters: + - $ref: "#/components/parameters/apiKeyParam" + - $ref: "#/components/parameters/queryParam" + - description: | + Autosuggest podcasts. This only searches podcast title and publisher and returns very limited info of 5 podcasts. 1 is yes, 0 is no. It's a bit slow to autosuggest podcasts, so we turn it off by default. If show_podcasts=1, you can also pass iTunes id (e.g., 474722933) to the q parameter to fetch podcast meta data. + explode: true + in: query + name: show_podcasts + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 1 + type: integer + style: form + - description: | + Whether or not to autosuggest genres. 1 is yes, 0 is no. + explode: true + in: query + name: show_genres + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 1 + type: integer + style: form + - description: | + Whether or not to exclude podcasts/episodes with explicit language. 1 is yes and 0 is no. It works only when **show_podcasts** is *1*. + explode: true + in: query + name: safe_mode + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 0 + type: integer + style: form + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/TypeaheadResponse" + description: OK + headers: + X-ListenAPI-FreeQuota: + $ref: "#/components/headers/X-ListenAPI-FreeQuota" + X-ListenAPI-NextBillingDate: + $ref: "#/components/headers/X-ListenAPI-NextBillingDate" + X-ListenAPI-Usage: + $ref: "#/components/headers/X-ListenAPI-Usage" + X-listenAPI-Latency-Seconds: + $ref: "#/components/headers/X-listenAPI-Latency-Seconds" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "429": + $ref: "#/components/responses/TooManyRequests" + "500": + $ref: "#/components/responses/ServerError" + summary: Typeahead search + tags: + - Search API +components: + headers: + X-ListenAPI-FreeQuota: + description: Free quotas of API requests included in your api plan. + explode: false + schema: + examples: + - 25000 + type: integer + style: simple + X-ListenAPI-NextBillingDate: + description: The timestamp for the start of next billing cycle. In ISO 8601 format. + schema: + examples: + - 2020-04-26T17:27:33.110641+00:00 + format: date-time + type: string + style: simple + X-ListenAPI-Usage: + description: The number of API requests that you've used in current billing cycle. + explode: false + schema: + examples: + - 19231 + type: integer + style: simple + X-listenAPI-Latency-Seconds: + description: Latency for this api call, in seconds. + explode: false + schema: + examples: + - 0.056 + type: number + style: simple + parameters: + apiKeyParam: + description: Get API Key on listennotes.com/api + explode: false + in: header + name: X-ListenAPI-Key + required: true + schema: + type: string + style: simple + genreIdParam: + description: You can get the id from `GET /genres`. If not specified, it'll be the overall best podcasts, which can be considered as a special genre. + in: query + name: genre_id + required: false + schema: + examples: + - 93 + type: string + queryParam: + description: | + Search term, e.g., person, place, topic... You can use double quotes to do verbatim match, e.g., "game of thrones". Otherwise, it's fuzzy search. + explode: true + in: query + name: q + required: true + schema: + examples: + - star wars + type: string + style: form + safeModeParam: + description: Whether or not to exclude podcasts with explicit language. 1 is yes, and 0 is no. + in: query + name: safe_mode + required: false + schema: + default: 0 + enum: + - 0 + - 1 + examples: + - 0 + type: integer + responses: + BadRequest: + description: Something wrong on your end (Client side errors), e.g., missing required parameters. + NotFound: + description: Endpoint not exist, or podcast / episode not exist. + ServerError: + description: Something wrong on our end (Unexpected server errors). + TooManyRequests: + description: For FREE plan, exceeding the quota limit; or for all plans, sending too many requests too fast and exceeding the rate limit. + Unauthorized: + description: Wrong api key, or your account is suspended. + schemas: + AudioField: + description: Audio url of this episode, which can be played directly. + examples: + - https://www.listennotes.com/e/p/11b34041e804491b9704d11f283c74de/ + type: string + AudioLengthSecField: + description: Audio length of this episode. In seconds. + examples: + - 567 + type: integer + AvgAudioLengthSecField: + description: Average audio length of all episodes of this podcast. In seconds. + examples: + - 1291 + type: integer + BestPodcastsLNUrlField: + description: Url of the list of best podcasts on [ListenNotes.com](https://www.ListenNotes.com). + examples: + - https://www.listennotes.com/best-business-news-podcasts-95/ + type: string + BestPodcastsResponse: + properties: + has_next: + examples: + - true + type: boolean + has_previous: + examples: + - true + type: boolean + id: + description: The id of this genre + examples: + - 95 + type: integer + listennotes_url: + $ref: "#/components/schemas/BestPodcastsLNUrlField" + name: + description: This genre's name. + examples: + - Business News + type: string + next_page_number: + examples: + - 3 + type: integer + page_number: + examples: + - 2 + type: integer + parent_id: + description: The id of parent genre. + examples: + - 93 + type: integer + podcasts: + items: + $ref: "#/components/schemas/PodcastSimple" + type: array + previous_page_number: + examples: + - 1 + type: integer + total: + examples: + - 325 + type: integer + required: + - has_next + - has_previous + - id + - listennotes_url + - name + - next_page_number + - page_number + - parent_id + - podcasts + - previous_page_number + - total + type: object + CountryField: + description: The country where this podcast is produced. + examples: + - United States + type: string + CuratedDescriptionField: + description: This curated list's description. + examples: + - Commuting to work is always better when you have a great new podcast to listen to, and this year, we have discovered some of our favorite podcasts yet for readers and book-lovers. These podcasts for readers entertain us and provide no shortage of new book recommendations too. + type: string + CuratedIdField: + description: Curated list id, which can be used to further fetch detailed curated list metadata via `GET /curated_podcasts/{id}`. + examples: + - Vb017Sx3l8F + type: string + CuratedLNUrlField: + description: The url of this curated list on [ListenNotes.com](https://www.ListenNotes.com). + examples: + - https://www.listennotes.com/curated-podcasts/7-bookish-podcasts-for-avid-readers-on-H2r-TCWai8K/ + type: string + CuratedListFull: + properties: + description: + $ref: "#/components/schemas/CuratedDescriptionField" + id: + $ref: "#/components/schemas/CuratedIdField" + listennotes_url: + $ref: "#/components/schemas/CuratedLNUrlField" + podcasts: + description: Complete meta data of all podcasts in this curated list. + items: + $ref: "#/components/schemas/PodcastSimple" + type: array + pub_date_ms: + $ref: "#/components/schemas/CuratedPubDateMsField" + source_domain: + $ref: "#/components/schemas/CuratedSourceDomainField" + source_url: + $ref: "#/components/schemas/CuratedSourceUrlField" + title: + $ref: "#/components/schemas/CuratedNameField" + total: + $ref: "#/components/schemas/CuratedTotalPodcastsField" + type: object + CuratedListSearchResult: + description: When **type** is *curated*. + properties: + description_highlighted: + description: Highlighted segment of this curated list's description + examples: + - ...Star Wars fans in Reddit shared their favorite podcasts. + type: string + description_original: + description: Plain text of this curated list's description + examples: + - Star Wars fans in Reddit shared their favorite podcasts. + type: string + id: + $ref: "#/components/schemas/CuratedIdField" + listennotes_url: + $ref: "#/components/schemas/CuratedLNUrlField" + podcasts: + description: Up to 5 podcasts in this curated list. + items: + $ref: "#/components/schemas/PodcastMinimum" + type: array + pub_date_ms: + $ref: "#/components/schemas/CuratedPubDateMsField" + source_domain: + $ref: "#/components/schemas/CuratedSourceDomainField" + source_url: + $ref: "#/components/schemas/CuratedSourceUrlField" + title_highlighted: + description: Highlighted segment of this curated list's title + examples: + - | + What are some good Star Wars Podcast to listen to? + type: string + title_original: + description: Plain text of this curated list's title + examples: + - What are some good Star Wars Podcast to listen to? + type: string + total: + $ref: "#/components/schemas/CuratedTotalPodcastsField" + type: object + CuratedListSimple: + properties: + description: + $ref: "#/components/schemas/CuratedDescriptionField" + id: + $ref: "#/components/schemas/CuratedIdField" + listennotes_url: + $ref: "#/components/schemas/CuratedLNUrlField" + podcasts: + description: Minimum meta data of up to 5 podcasts in this curated list. + items: + $ref: "#/components/schemas/PodcastMinimum" + type: array + pub_date_ms: + $ref: "#/components/schemas/CuratedPubDateMsField" + source_domain: + $ref: "#/components/schemas/CuratedSourceDomainField" + source_url: + $ref: "#/components/schemas/CuratedSourceUrlField" + title: + $ref: "#/components/schemas/CuratedNameField" + total: + $ref: "#/components/schemas/CuratedTotalPodcastsField" + type: object + CuratedNameField: + description: Curated list name. + examples: + - 7 Bookish Podcasts for Avid Readers On the Go + type: string + CuratedPubDateMsField: + description: Published date of this curated list. In milliseconds. + examples: + - 1556843484301 + type: integer + CuratedSourceDomainField: + description: The domain name of the source of this curated list. + examples: + - parade.com + type: string + CuratedSourceUrlField: + description: Url of the source of this curated list. + examples: + - https://parade.com/718913/ashley_johnson/7-bookish-podcasts-for-avid-readers-on-the-go/ + type: string + CuratedTotalPodcastsField: + description: The total number of podcasts in this curated list. + examples: + - 25 + type: integer + CustomAudio: + description: A custom audio in a playlist, which is a type of playlist item. + properties: + audio: + description: Audio url, which can be played directly. + examples: + - https://example.com/audio.mp3 + type: string + audio_length_sec: + description: Audio length in seconds. + examples: + - 253 + type: integer + image: + description: High resolution image url of this custom audio. + examples: + - https://cdn-images-1.listennotes.com/playlist/image/6907e8ff6b6c45df94cc059753f369cc.JPEG + type: string + pub_date_ms: + description: | + Published date (in milliseconds) of this custom audio. + For now, it's the same as **added_at_ms** of this playlist item. + examples: + - 1595567028133 + type: integer + thumbnail: + description: Low resolution image url of this custom audio. + examples: + - https://d3sv2eduhewoas.cloudfront.net/playlist/image/48477deae02649d7ab9d3f1b3966af38.JPEG + type: string + title: + description: Custom audio title. + examples: + - An awesome audio to listen. + type: string + type: object + DeletePodcastResponse: + properties: + status: + description: The status of this podcast deletion request. + enum: + - deleted + - in review + examples: + - deleted + type: string + required: + - status + type: object + DeletedItem: + description: | + A deleted episode or podcast. + An episode or a podcast could be deleted from our podcast database. + Possible reasons: 1) Podcast producers sometimes delete their old episodes. 2) Copyright issues. + properties: + error: + description: Why this episode or podcast is deleted? + examples: + - This episode is deleted from the podcast database, because... + type: string + id: + description: Episode id or podcast id. + examples: + - 96fc400171364e32897b25d84a8ed8ec + type: string + status: + description: The status of this episode or podcast. For now, the only possible value is **deleted**. + examples: + - deleted + type: string + title: + description: Episode title or podcast title. + examples: + - This is a test episode + type: string + type: object + EarliestPubDateMsField: + description: The published date of the oldest episode of this podcast. In milliseconds + examples: + - 1470667902000 + type: integer + EmailField: + description: The email of this podcast's producer. This field is available only in the PRO/ENTERPRISE plan. + examples: + - hello@example.com + type: string + EpisodeDescriptionField: + description: Html of this episode's full description + examples: + - | +

Disney chief Bob Iger shared news about Star Wars movies in 2020 and beyond, but some media outlets gave conflicting reports about it. Here's the real scoop. Punch it!

***We’re listener supported! Go to http://Patreon.com/sw7x7 to donate to the Star Wars 7x7 podcast, and you’ll get some fabulous rewards for your pledge.*** 

Check out SW7x7.com for full Star Wars 7x7 show notes and links, and to comment on any of the content of this episode! If you like what you've heard, please leave us a rating or review on iTunes or Stitcher, which will also help more people discover this Star Wars podcast.

Don't forget to join the Star Wars 7x7 fun on Facebook at Facebook.com/SW7x7, and follow the breaking news Twitter feed at Twitter.com/SW7x7Podcast. We're also on Pinterest and Instagram as "SW7x7" too, and we'd love to connect with you there!

+ type: string + EpisodeFull: + properties: + audio: + $ref: "#/components/schemas/AudioField" + audio_length_sec: + $ref: "#/components/schemas/AudioLengthSecField" + description: + $ref: "#/components/schemas/EpisodeDescriptionField" + explicit_content: + $ref: "#/components/schemas/ExplicitField" + id: + $ref: "#/components/schemas/EpisodeIdField" + image: + $ref: "#/components/schemas/EpisodeImageField" + link: + $ref: "#/components/schemas/LinkField" + listennotes_edit_url: + $ref: "#/components/schemas/EpisodeLNEditUrlField" + listennotes_url: + $ref: "#/components/schemas/EpisodeLNUrlField" + maybe_audio_invalid: + $ref: "#/components/schemas/MaybeAudioInvalidField" + podcast: + $ref: "#/components/schemas/PodcastSimple" + pub_date_ms: + $ref: "#/components/schemas/EpisodePubDateMsField" + thumbnail: + $ref: "#/components/schemas/EpisodeThumbnailField" + title: + $ref: "#/components/schemas/EpisodeNameField" + transcript: + $ref: "#/components/schemas/TranscriptField" + type: object + EpisodeIdField: + description: Episode id, which can be used to further fetch detailed episode metadata via `GET /episodes/{id}`. + examples: + - 4d82e50314174754a3b603912448e812 + type: string + EpisodeImageField: + description: | + Image url for this episode. + If an episode doesn't have its own image, then this field would be the url of the podcast artwork image. + If you are using PRO/ENTERPRISE plan, then it's + a high resolution image (1400x1400). If you are using FREE plan, then it's the same as **thumbnail**, + low resolution image (300x300). + examples: + - https://cdn-images-1.listennotes.com/podcasts/exponent-ben-thompson-james-allworth-OaJSjb4xQv3.1400x1400.jpg + type: string + EpisodeLNEditUrlField: + description: Edit url of this episode where you can update the audio url if you find the audio is broken. + examples: + - https://www.listennotes.com/e/11b34041e804491b9704d11f283c74de/#edit + type: string + EpisodeLNUrlField: + description: The url of this episode on [ListenNotes.com](https://www.ListenNotes.com). + examples: + - https://www.listennotes.com/e/4d82e50314174754a3b603912448e812/ + type: string + EpisodeMinimum: + properties: + audio: + $ref: "#/components/schemas/AudioField" + audio_length_sec: + $ref: "#/components/schemas/AudioLengthSecField" + description: + $ref: "#/components/schemas/EpisodeDescriptionField" + explicit_content: + $ref: "#/components/schemas/ExplicitField" + id: + $ref: "#/components/schemas/EpisodeIdField" + image: + $ref: "#/components/schemas/ImageField" + link: + $ref: "#/components/schemas/LinkField" + listennotes_edit_url: + $ref: "#/components/schemas/EpisodeLNEditUrlField" + listennotes_url: + $ref: "#/components/schemas/EpisodeLNUrlField" + maybe_audio_invalid: + $ref: "#/components/schemas/MaybeAudioInvalidField" + pub_date_ms: + $ref: "#/components/schemas/EpisodePubDateMsField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title: + $ref: "#/components/schemas/EpisodeNameField" + type: object + EpisodeNameField: + description: Episode name. + examples: + - "Celebration Recap, Jason Fry and Christian Blauvelt Interviews – SWBW #101" + type: string + EpisodePubDateMsField: + description: Published date for this episode. In millisecond. + examples: + - 1474873200000 + type: integer + EpisodeSearchResult: + description: When **type** is *episode*. + properties: + audio: + $ref: "#/components/schemas/AudioField" + audio_length_sec: + $ref: "#/components/schemas/AudioLengthSecField" + description_highlighted: + description: Highlighted segment of this episode's description + examples: + - | + ...Go to http://Patreon.com/sw7x7 to donate to the Star Wars 7x7 podcast, and you'll get some fabulous rewards for your pledge.*** Check out SW7x7.com for full Star Wars 7x7 show notes and links, and to + type: string + description_original: + description: Plain text of this episode's description + examples: + - | + Yeah, Star Wars Celebration Orlando is 32 days away, but what's the scoop on Celebration 2018? Plus, Rebels Day is Saturday, and much more in our update. Punch it! ***We're listener supported! Go to http://Patreon.com/sw7x7 to donate to the Star Wars 7x7 podcast, and you’ll get some fabulous rewards for your pledge.*** Check out SW7x7.com for full Star Wars 7x7 show notes and links, and to comment on any of the content of this episode! If you like what you've heard, please leave us a rating or review on iTunes or Stitcher, which will also help more people discover this Star Wars podcast. Don't forget to join the Star Wars 7x7 fun on Facebook at Facebook.com/SW7x7, and follow the breaking news Twitter feed at Twitter.com/SW7x7Podcast. We're also on Pinterest and Instagram as "SW7x7" too, and we'd love to connect with you there! + type: string + explicit_content: + $ref: "#/components/schemas/ExplicitField" + id: + $ref: "#/components/schemas/EpisodeIdField" + image: + $ref: "#/components/schemas/EpisodeImageField" + itunes_id: + $ref: "#/components/schemas/iTunesIdField" + link: + $ref: "#/components/schemas/LinkField" + listennotes_url: + $ref: "#/components/schemas/EpisodeLNUrlField" + podcast: + description: The podcast that this episode belongs to. + properties: + genre_ids: + $ref: "#/components/schemas/GenreIdsField" + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + listen_score: + $ref: "#/components/schemas/ListenScoreField" + listen_score_global_rank: + $ref: "#/components/schemas/ListenScoreGlobalRankField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + publisher_highlighted: + $ref: "#/components/schemas/PublisherHighlightedField" + publisher_original: + $ref: "#/components/schemas/PublisherOriginalField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title_highlighted: + $ref: "#/components/schemas/PodcastTitleHighlightedField" + title_original: + $ref: "#/components/schemas/PodcastTitleOriginalField" + type: object + pub_date_ms: + $ref: "#/components/schemas/EpisodePubDateMsField" + rss: + $ref: "#/components/schemas/RssField" + thumbnail: + $ref: "#/components/schemas/EpisodeThumbnailField" + title_highlighted: + description: Highlighted segment of this episode's title + examples: + - '815: Star Wars 2020 Movie and Beyond!' + type: string + title_original: + description: Plain text of this episode' title + examples: + - "815: Star Wars 2020 Movie and Beyond!" + type: string + transcripts_highlighted: + description: Up to 2 highlighted segments of the audio transcript of this episode. + items: + examples: + - | + 00:21:27 when Disney bought the Star Wars franchise from George Lucas they had a plan lots of Star Wars movies new Star Wars movies every month another one was just released while I was talking + type: string + type: array + type: object + EpisodeSimple: + properties: + audio: + $ref: "#/components/schemas/AudioField" + audio_length_sec: + $ref: "#/components/schemas/AudioLengthSecField" + description: + $ref: "#/components/schemas/EpisodeDescriptionField" + explicit_content: + $ref: "#/components/schemas/ExplicitField" + id: + $ref: "#/components/schemas/EpisodeIdField" + image: + $ref: "#/components/schemas/EpisodeImageField" + link: + $ref: "#/components/schemas/LinkField" + listennotes_edit_url: + $ref: "#/components/schemas/EpisodeLNEditUrlField" + listennotes_url: + $ref: "#/components/schemas/EpisodeLNUrlField" + maybe_audio_invalid: + $ref: "#/components/schemas/MaybeAudioInvalidField" + podcast: + $ref: "#/components/schemas/PodcastMinimum" + pub_date_ms: + $ref: "#/components/schemas/EpisodePubDateMsField" + thumbnail: + $ref: "#/components/schemas/EpisodeThumbnailField" + title: + $ref: "#/components/schemas/EpisodeNameField" + type: object + EpisodeThumbnailField: + description: | + Thumbnail image (300x300) url for this episode. + If an episode doesn't have its own image, then this field would be the url of the podcast artwork thumbnail image. + examples: + - https://cdn-images-1.listennotes.com/podcasts/exponent-ben-thompson-james-allworth-OaJSjb4xQv3.300x300.jpg + type: string + ExplicitField: + description: Whether this podcast contains explicit language. + examples: + - false + type: boolean + Genre: + examples: + - id: 140 + name: Web Design + parent_id: 127 + properties: + id: + description: Genre id + examples: + - 93 + type: integer + name: + description: Genre name. + examples: + - Business + type: string + parent_id: + description: Parent genre id. + examples: + - 95 + type: integer + type: object + GenreIdsField: + examples: + - - 138 + - 86 + - 160 + - 68 + - 82 + - 100 + - 101 + items: + description: Genre ids. + type: integer + type: array + GetCuratedPodcastsResponse: + properties: + curated_lists: + items: + $ref: "#/components/schemas/CuratedListSimple" + type: array + has_next: + examples: + - true + type: boolean + has_previous: + examples: + - true + type: boolean + next_page_number: + examples: + - 3 + type: integer + page_number: + examples: + - 2 + type: integer + previous_page_number: + examples: + - 1 + type: integer + total: + examples: + - 25 + type: integer + required: + - curated_lists + - has_next + - has_previous + - next_page_number + - page_number + - previous_page_number + - total + type: object + GetEpisodeRecommendationsResponse: + properties: + recommendations: + items: + $ref: "#/components/schemas/EpisodeSimple" + type: array + required: + - recommendations + type: object + GetEpisodesInBatchForm: + properties: + ids: + description: Comma-separated list of episode ids. + examples: + - c577d55b2b2b483c969fae3ceb58e362,0f34a9099579490993eec9e8c8cebb82 + type: string + required: + - ids + type: object + GetEpisodesInBatchResponse: + properties: + episodes: + items: + $ref: "#/components/schemas/EpisodeSimple" + type: array + required: + - episodes + type: object + GetGenresResponse: + properties: + genres: + items: + $ref: "#/components/schemas/Genre" + type: array + required: + - genres + type: object + GetLanguagesResponse: + properties: + languages: + examples: + - - Any language + - Afar + - Abkhazian + - Afrikaans + - Akan + - Albanian + - Arabic + - Azerbaijani + - Bambara + - Bashkir + - Basque + - Belarusian + - Bulgarian + - Catalan + - Chamorro + - Chinese + - Croatian + - Czech + - Danish + - Dutch + - English + - Estonian + - Faeroese + - Finnish + - French + - Gaelic + - Galician + - German + - Greek + items: + type: string + type: array + required: + - languages + type: object + GetPodcastRecommendationsResponse: + properties: + recommendations: + items: + $ref: "#/components/schemas/PodcastSimple" + type: array + required: + - recommendations + type: object + GetPodcastsInBatchForm: + properties: + ids: + description: Comma-separated list of podcast ids. + examples: + - 3302bc71139541baa46ecb27dbf6071a,68faf62be97149c280ebcc25178aa731,37589a3e121e40debe4cef3d9638932a,9cf19c590ff0484d97b18b329fed0c6a + type: string + itunes_ids: + description: Comma-separated Apple Podcasts (iTunes) ids, e.g., 659155419 + examples: + - 1457514703,1386234384,659155419 + type: string + next_episode_pub_date: + description: | + For latest episodes pagination. It's the value of **next_episode_pub_date** from the response of last request. If not specified, just return latest 15 episodes. + examples: + - 1557394247000 + type: integer + rsses: + description: Comma-separated rss urls. + examples: + - https://rss.art19.com/recode-decode,https://rss.art19.com/the-daily,https://www.npr.org/rss/podcast.php?id=510331,https://www.npr.org/rss/podcast.php?id=510331 + type: string + show_latest_episodes: + default: 0 + description: | + Whether or not to fetch up to 15 latest episodes from these podcasts, sorted by pub_date. 1 is yes, and 0 is no. + enum: + - 0 + - 1 + examples: + - 1 + type: integer + spotify_ids: + description: Comma-separated Spotify ids, e.g., 3DDfEsKDIDrTlnPOiG4ZF4 + examples: + - 3DDfEsKDIDrTlnPOiG4ZF4,4qDNe5Gvl1XxdLinUGEXrC,23NZCM4ik6o3UYkM473Itz + type: string + type: object + GetPodcastsInBatchResponse: + properties: + latest_episodes: + description: | + Up to 10 latest episodes from these podcasts, sorted by **pub_date**. This field shows up only when **show_latest_episodes** is 1. + items: + $ref: "#/components/schemas/EpisodeSimple" + type: array + podcasts: + items: + $ref: "#/components/schemas/PodcastSimple" + type: array + required: + - podcasts + type: object + GetRegionsResponse: + properties: + regions: + examples: + - au: Australia + de: Germany + ua: Ukraine + us: United States + type: object + required: + - regions + type: object + ImageField: + description: | + Image url for this podcast's artwork. If you are using PRO/ENTERPRISE plan, then it's + a high resolution image (1400x1400). If you are using FREE plan, then it's the same as **thumbnail**, + low resolution image (300x300). + examples: + - https://cdn-images-1.listennotes.com/podcasts/exponent-ben-thompson-james-allworth-OaJSjb4xQv3.1400x1400.jpg + type: string + IsClaimedField: + description: Whether this podcast is claimed by its producer on [ListenNotes.com](https://www.ListenNotes.com). + examples: + - true + type: boolean + LanguageField: + description: The language of this podcast. You can get all supported languages from `GET /languages`. + examples: + - English + type: string + LatestEpisodeIdField: + description: The id of the most recently published episode of this podcast, which can be used to further fetch detailed episode metadata via `GET /episodes/{id}`. + examples: + - d057092e57cc4ced80e0efaa196593d9 + type: string + LatestPubDateMsField: + description: The published date of the latest episode of this podcast. In milliseconds + examples: + - 1557499770000 + type: integer + LinkField: + description: Web link of this episode. + examples: + - https://www.npr.org/2020/01/22/798532179/soleimanis-iran + type: string + ListenScoreField: + description: | + The estimated popularity score of a podcast compared to all other rss-based public podcasts in the world on a scale from 0 to 100. + If the score is not available, it'll be null. Learn more at listennotes.com/listen-score + examples: + - 81 + type: integer + ListenScoreGlobalRankField: + description: | + The estimated popularity ranking of a podcast compared to all other rss-based public podcasts in the world. + For example, if the value is 0.5%, then this podcast is one of the top 0.5% most popular shows out of all podcasts globally, ranked by Listen Score. + If the ranking is not available, it'll be null. Learn more at listennotes.com/listen-score + examples: + - 0.5% + type: string + MaybeAudioInvalidField: + description: Whether or not this episode's audio is invalid. Podcasters may delete the original audio. + examples: + - false + type: boolean + NextEpisodePubDateField: + description: Passed to the **next_episode_pub_date** parameter of `GET /podcasts/{id}` to paginate through episodes of that podcast. + examples: + - 1470667902000 + type: integer + PlaylistDescriptionField: + description: Playlist description. + examples: + - A curated playlist of podcasts about podcasting. + type: string + PlaylistIdField: + description: A 11-character playlist id, which can be used to further fetch detailed playlist metadata via `GET /playlists/{id}`. + examples: + - m1pe7z60bsw + type: string + PlaylistImageField: + description: High resolution image url of the playlist. + examples: + - https://cdn-images-1.listennotes.com/playlist/image/6907e8ff6b6c45df94cc059753f369cc.JPEG + type: string + PlaylistItem: + description: An item in a playlist + properties: + added_at_ms: + description: Timestamp (in milliseconds) when this item is added. + examples: + - 1595567004958 + type: integer + data: + oneOf: + - $ref: "#/components/schemas/EpisodeSimple" + - $ref: "#/components/schemas/PodcastSimple" + - $ref: "#/components/schemas/CustomAudio" + - $ref: "#/components/schemas/DeletedItem" + id: + description: Playlist item id. + examples: + - 23 + type: integer + notes: + description: Notes for this item. + examples: + - This is a good episode. + type: string + type: + description: | + The type of this playlist item. + If a playlist is **episode_list**, then an item could be either **episode** or **custom_audio**. + If it's **podcast_list**, then an item can only be **podcast**. + enum: + - episode + - custom_audio + - podcast + examples: + - episode + type: string + type: object + PlaylistLastTimestampMsField: + description: | + Passed to the **last_timestamp_ms** parameter of `GET /playlists/{id}` to paginate through items of that playlist. + examples: + - 1595641092907 + type: integer + PlaylistListennotesUrlField: + description: The url of this playlist on ListenNotes.com. + examples: + - https://www.listennotes.com/listen/podcasts-about-podcasting-m1pe7z60bsw/?display=episode + type: string + PlaylistNameField: + description: Playlist name. + examples: + - My podcast playlist + type: string + PlaylistResponse: + properties: + description: + $ref: "#/components/schemas/PlaylistDescriptionField" + id: + $ref: "#/components/schemas/PlaylistIdField" + image: + $ref: "#/components/schemas/PlaylistImageField" + items: + description: A list of playlist items. + items: + $ref: "#/components/schemas/PlaylistItem" + type: array + last_timestamp_ms: + $ref: "#/components/schemas/PlaylistLastTimestampMsField" + listennotes_url: + $ref: "#/components/schemas/PlaylistListennotesUrlField" + name: + $ref: "#/components/schemas/PlaylistNameField" + thumbnail: + $ref: "#/components/schemas/PlaylistThumbnailField" + total: + description: Total number of items in this playlist. + examples: + - 325 + type: integer + total_audio_length_sec: + description: Total audio length of all episodes in this playlist, in seconds. It will have a valid value only when type is **episode_list**. In other words, it will be 0 if type is **podcast_list**. + examples: + - 234567 + type: integer + type: + description: | + The type of this playlist, which should be either **episode_list** or **podcast_list**. + enum: + - episode_list + - podcast_list + examples: + - episode_list + type: string + visibility: + $ref: "#/components/schemas/PlaylistVisibilityField" + type: object + PlaylistThumbnailField: + description: Low resolution image url of the playlist. + examples: + - https://d3sv2eduhewoas.cloudfront.net/playlist/image/48477deae02649d7ab9d3f1b3966af38.JPEG + type: string + PlaylistVisibilityField: + description: Visibility of this playlist. + enum: + - public + - unlisted + - private + examples: + - public + type: string + PlaylistsResponse: + properties: + has_next: + examples: + - true + type: boolean + has_previous: + examples: + - true + type: boolean + next_page_number: + examples: + - 3 + type: integer + page_number: + examples: + - 2 + type: integer + playlists: + items: + description: A playlist + properties: + description: + $ref: "#/components/schemas/PlaylistDescriptionField" + episode_count: + description: The number of episodes (including custom audio) in this playlist. + examples: + - 23 + type: integer + id: + $ref: "#/components/schemas/PlaylistIdField" + image: + $ref: "#/components/schemas/PlaylistImageField" + last_timestamp_ms: + $ref: "#/components/schemas/PlaylistLastTimestampMsField" + listennotes_url: + $ref: "#/components/schemas/PlaylistListennotesUrlField" + name: + $ref: "#/components/schemas/PlaylistNameField" + podcast_count: + description: The number of podcasts in this playlist. + examples: + - 10 + type: integer + thumbnail: + $ref: "#/components/schemas/PlaylistThumbnailField" + total_audio_length_sec: + description: Total audio length of all episodes in this playlist, in seconds. + examples: + - 234567 + type: integer + visibility: + $ref: "#/components/schemas/PlaylistVisibilityField" + type: object + type: array + previous_page_number: + examples: + - 1 + type: integer + total: + examples: + - 325 + type: integer + type: object + PodcastAudienceResponse: + properties: + by_regions: + items: + properties: + ratio: + description: percentage of audience from this specific region + examples: + - 20.22% + type: string + region: + description: 2-letter country code of a region. + examples: + - us + type: string + type: object + type: array + type: object + PodcastDescriptionField: + description: Html of this episode's full description + examples: + -

The Star Wars 7x7 Podcast is Rebel-rousing fun for everyday Jedi, between 7 and 14 minutes a day, 7 days a week. Join host Allen Voivod for Star Wars news, history, interviews, trivia, and deep dives into the Star Wars story as told in movies, books, comics, games, cartoons, and more. Subscribe now for your daily dose of Star Wars joy. It's destiny unleashed!

+ type: string + PodcastDomainResponse: + properties: + has_next: + examples: + - true + type: boolean + has_previous: + examples: + - true + type: boolean + next_page_number: + examples: + - 3 + type: integer + page_number: + examples: + - 2 + type: integer + podcasts: + items: + $ref: "#/components/schemas/PodcastSimple" + type: array + previous_page_number: + examples: + - 1 + type: integer + type: object + PodcastExtraField: + properties: + amazon_music_url: + description: Amazon Music url for this podcast + examples: + - https://music.amazon.com/podcasts/6fc6d683-9ef3-4850-9c35-8e8b1a42a147/the-lock-sportscast + type: string + facebook_handle: + description: Facebook username affiliated with this podcast + examples: + - sw7x7 + type: string + google_url: + description: Google Podcasts url for this podcast + examples: + - https://podcasts.google.com/feed/aHR0cHM6Ly9yc3MuYXJ0MTkuY29tL2pvaG4tc29sb21vbi1yZXBvcnRz + type: string + instagram_handle: + description: Instagram username affiliated with this podcast + examples: + - sw7x7 + type: string + linkedin_url: + description: LinkedIn url affiliated with this podcast + type: string + patreon_handle: + description: Patreon username affiliated with this podcast + examples: + - sw7x7 + type: string + spotify_url: + description: Spotify url for this podcast + examples: + - https://open.spotify.com/show/2rQJUP9Y3HxemiW3JHt9WV + type: string + twitter_handle: + description: Twitter username affiliated with this podcast + examples: + - SW7x7podcast + type: string + url1: + description: Url affiliated with this podcast + type: string + url2: + description: Url affiliated with this podcast + type: string + url3: + description: Url affiliated with this podcast + type: string + wechat_handle: + description: WeChat username affiliated with this podcast + type: string + youtube_url: + description: YouTube url affiliated with this podcast + examples: + - https://www.youtube.com/sw7x7 + type: string + type: object + PodcastFull: + properties: + audio_length_sec: + $ref: "#/components/schemas/AvgAudioLengthSecField" + country: + $ref: "#/components/schemas/CountryField" + description: + $ref: "#/components/schemas/PodcastDescriptionField" + earliest_pub_date_ms: + $ref: "#/components/schemas/EarliestPubDateMsField" + email: + $ref: "#/components/schemas/EmailField" + episodes: + items: + $ref: "#/components/schemas/EpisodeMinimum" + type: array + explicit_content: + $ref: "#/components/schemas/ExplicitField" + extra: + $ref: "#/components/schemas/PodcastExtraField" + genre_ids: + $ref: "#/components/schemas/GenreIdsField" + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + is_claimed: + $ref: "#/components/schemas/IsClaimedField" + itunes_id: + $ref: "#/components/schemas/iTunesIdField" + language: + $ref: "#/components/schemas/LanguageField" + latest_episode_id: + $ref: "#/components/schemas/LatestEpisodeIdField" + latest_pub_date_ms: + $ref: "#/components/schemas/LatestPubDateMsField" + listen_score: + $ref: "#/components/schemas/ListenScoreField" + listen_score_global_rank: + $ref: "#/components/schemas/ListenScoreGlobalRankField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + looking_for: + $ref: "#/components/schemas/PodcastLookingForField" + next_episode_pub_date: + $ref: "#/components/schemas/NextEpisodePubDateField" + publisher: + $ref: "#/components/schemas/PublisherField" + rss: + $ref: "#/components/schemas/RssField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title: + $ref: "#/components/schemas/PodcastNameField" + total_episodes: + $ref: "#/components/schemas/TotalEpisodesField" + type: + $ref: "#/components/schemas/PodcastTypeField" + update_frequency_hours: + $ref: "#/components/schemas/UpdateFrequencyHoursField" + website: + $ref: "#/components/schemas/WebsiteField" + type: object + PodcastIdField: + description: Podcast id, which can be used to further fetch detailed podcast metadata via `GET /podcasts/{id}`. + examples: + - 4d3fe717742d4963a85562e9f84d8c79 + type: string + PodcastLNUrlField: + description: The url of this podcast on [ListenNotes.com](https://www.ListenNotes.com). + examples: + - https://www.listennotes.com/c/4d3fe717742d4963a85562e9f84d8c79/ + type: string + PodcastLookingForField: + properties: + cohosts: + description: Whether this podcast is looking for cohosts. + examples: + - true + type: boolean + cross_promotion: + description: Whether this podcast is looking for cross promotion opportunities with other podcasts. + examples: + - true + type: boolean + guests: + description: Whether this podcast is looking for guests. + examples: + - true + type: boolean + sponsors: + description: Whether this podcast is looking for sponsors. + examples: + - true + type: boolean + type: object + PodcastMinimum: + properties: + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + listen_score: + $ref: "#/components/schemas/ListenScoreField" + listen_score_global_rank: + $ref: "#/components/schemas/ListenScoreGlobalRankField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + publisher: + $ref: "#/components/schemas/PublisherField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title: + $ref: "#/components/schemas/PodcastNameField" + type: object + PodcastMinimumRss: + properties: + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + publisher: + $ref: "#/components/schemas/PublisherField" + rss: + $ref: "#/components/schemas/RssField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title: + $ref: "#/components/schemas/PodcastNameField" + type: object + PodcastNameField: + description: Podcast name. + examples: + - Star Wars 7x7 | Star Wars News, Interviews, and More! + type: string + PodcastSearchResult: + description: When **type** is *podcast*. + properties: + audio_length_sec: + $ref: "#/components/schemas/AvgAudioLengthSecField" + description_highlighted: + description: Highlighted segment of podcast description + examples: + - | + ...Join host Allen Voivod for Star Wars news, history, interviews, trivia, and deep dives into the Star Wars story as told in movies, books, comics, games, cartoons, and more. + type: string + description_original: + description: Plain text of podcast description + examples: + - | + The Star Wars 7x7 Podcast is Rebel-rousing fun for everyday Jedi, between 7 and 14 minutes a day, 7 days a week. Join host Allen Voivod for Star Wars news, history, interviews, trivia, and deep dives into the Star Wars story as told in movies, books, comics, games, cartoons, and more. Subscribe now for your daily dose of Star Wars joy. It's destiny unleashed! #SW7x7 + type: string + earliest_pub_date_ms: + $ref: "#/components/schemas/EarliestPubDateMsField" + email: + $ref: "#/components/schemas/EmailField" + explicit_content: + $ref: "#/components/schemas/ExplicitField" + genre_ids: + $ref: "#/components/schemas/GenreIdsField" + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + itunes_id: + $ref: "#/components/schemas/iTunesIdField" + latest_episode_id: + $ref: "#/components/schemas/LatestEpisodeIdField" + latest_pub_date_ms: + $ref: "#/components/schemas/LatestPubDateMsField" + listen_score: + $ref: "#/components/schemas/ListenScoreField" + listen_score_global_rank: + $ref: "#/components/schemas/ListenScoreGlobalRankField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + publisher_highlighted: + $ref: "#/components/schemas/PublisherHighlightedField" + publisher_original: + $ref: "#/components/schemas/PublisherOriginalField" + rss: + $ref: "#/components/schemas/RssField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title_highlighted: + $ref: "#/components/schemas/PodcastTitleHighlightedField" + title_original: + $ref: "#/components/schemas/PodcastTitleOriginalField" + total_episodes: + $ref: "#/components/schemas/TotalEpisodesField" + update_frequency_hours: + $ref: "#/components/schemas/UpdateFrequencyHoursField" + website: + $ref: "#/components/schemas/WebsiteField" + type: object + PodcastSimple: + properties: + audio_length_sec: + $ref: "#/components/schemas/AvgAudioLengthSecField" + country: + $ref: "#/components/schemas/CountryField" + description: + $ref: "#/components/schemas/PodcastDescriptionField" + earliest_pub_date_ms: + $ref: "#/components/schemas/EarliestPubDateMsField" + email: + $ref: "#/components/schemas/EmailField" + explicit_content: + $ref: "#/components/schemas/ExplicitField" + extra: + $ref: "#/components/schemas/PodcastExtraField" + genre_ids: + $ref: "#/components/schemas/GenreIdsField" + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + is_claimed: + $ref: "#/components/schemas/IsClaimedField" + itunes_id: + $ref: "#/components/schemas/iTunesIdField" + language: + $ref: "#/components/schemas/LanguageField" + latest_episode_id: + $ref: "#/components/schemas/LatestEpisodeIdField" + latest_pub_date_ms: + $ref: "#/components/schemas/LatestPubDateMsField" + listen_score: + $ref: "#/components/schemas/ListenScoreField" + listen_score_global_rank: + $ref: "#/components/schemas/ListenScoreGlobalRankField" + listennotes_url: + $ref: "#/components/schemas/PodcastLNUrlField" + looking_for: + $ref: "#/components/schemas/PodcastLookingForField" + publisher: + $ref: "#/components/schemas/PublisherField" + rss: + $ref: "#/components/schemas/RssField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title: + $ref: "#/components/schemas/PodcastNameField" + total_episodes: + $ref: "#/components/schemas/TotalEpisodesField" + type: + $ref: "#/components/schemas/PodcastTypeField" + update_frequency_hours: + $ref: "#/components/schemas/UpdateFrequencyHoursField" + website: + $ref: "#/components/schemas/WebsiteField" + type: object + PodcastTitleHighlightedField: + description: Highlighted segment of podcast name. + examples: + - Star Wars 7x7 | Star Wars News, Interviews, and More! + type: string + PodcastTitleOriginalField: + description: Plain text of podcast name. + examples: + - Star Wars 7x7 | Star Wars News, Interviews, and More! + type: string + PodcastTypeField: + description: The type of this podcast - episodic or serial. + enum: + - episodic + - serial + examples: + - episodic + type: string + PodcastTypeaheadResult: + properties: + explicit_content: + $ref: "#/components/schemas/ExplicitField" + id: + $ref: "#/components/schemas/PodcastIdField" + image: + $ref: "#/components/schemas/ImageField" + publisher_highlighted: + $ref: "#/components/schemas/PublisherHighlightedField" + publisher_original: + $ref: "#/components/schemas/PublisherOriginalField" + thumbnail: + $ref: "#/components/schemas/ThumbnailField" + title_highlighted: + $ref: "#/components/schemas/PodcastTitleHighlightedField" + title_original: + $ref: "#/components/schemas/PodcastTitleOriginalField" + type: object + PublisherField: + description: Podcast publisher name. + examples: + - Planet Broadcasting + type: string + PublisherHighlightedField: + description: Highlighted segment of this podcast's publisher name. + examples: + - Star Wars Daily, by Allen Voivod + type: string + PublisherOriginalField: + description: Plain text of this podcast's publisher name. + examples: + - Star Wars Daily, by Allen Voivod + type: string + RelatedSearchesResponse: + properties: + terms: + description: Related search terms + examples: + - - evergrande stock + - evergrande china + - evergrande group + - evergrande news + items: + type: string + type: array + required: + - terms + type: object + RssField: + description: RSS url of this podcast. This field is available only in the PRO/ENTERPRISE plan. + examples: + - https://sw7x7.libsyn.com/rss + type: string + SearchResponse: + properties: + count: + description: The number of search results in this page. + examples: + - 10 + type: integer + next_offset: + description: Pass this value to the **offset** parameter to do pagination of search results. + examples: + - 10 + type: integer + results: + description: A list of search results. + items: + oneOf: + - $ref: "#/components/schemas/EpisodeSearchResult" + - $ref: "#/components/schemas/PodcastSearchResult" + - $ref: "#/components/schemas/CuratedListSearchResult" + type: array + took: + description: The time it took to fetch these search results. In seconds. + examples: + - 0.093 + type: number + total: + description: The total number of search results. + examples: + - 1989 + type: integer + type: object + SpellCheckResponse: + properties: + corrected_text_html: + description: The corrected text for the entire search term (multiple words/tokens), where misspelled tokens are replaced with the correct texts and html tags + examples: + - evergrande stock + type: string + tokens: + description: The word in the text query string that is not spelled correctly + items: + properties: + offset: + description: The zero-based offset from the beginning of the text query string to the word that is misspelled + examples: + - 5 + type: integer + suggestion: + description: A word that corrects the spelling error + examples: + - evergrande + type: string + token: + description: The misspelled word + examples: + - evergrand + type: string + type: object + type: array + required: + - tokens + - corrected_text_html + type: object + SubmitPodcastForm: + properties: + email: + description: A valid email address. If **email** is specified, then we'll notify this email address once the podcast is accepted. + examples: + - hello@example.com + type: string + rss: + description: A valid podcast rss url. + examples: + - https://feeds.megaphone.fm/committed + type: string + required: + - rss + type: object + SubmitPodcastResponse: + properties: + podcast: + $ref: "#/components/schemas/PodcastMinimum" + status: + description: The status of this submission. + enum: + - found + - in review + - rejected + examples: + - found + type: string + required: + - podcast + - status + type: object + ThumbnailField: + description: Thumbnail image url for this podcast's artwork (300x300). + examples: + - https://cdn-images-1.listennotes.com/podcasts/exponent-ben-thompson-james-allworth-OaJSjb4xQv3.300x300.jpg + type: string + TotalEpisodesField: + description: Total number of episodes in this podcast. + examples: + - 324 + type: integer + TranscriptField: + description: The transcript of this episode, in plain text (with the newline character \n). If there's not transcript, it is null. This field is available only in the PRO/ENTERPRISE plan. + examples: + - | + 00:00:07 Welcome to this podcast... + type: string + TrendingSearchesResponse: + properties: + terms: + description: Trending search terms + examples: + - - Taliban + - Andrew Cuomo + - john McAfee + items: + type: string + type: array + required: + - terms + type: object + TypeaheadResponse: + properties: + genres: + description: Genre suggestions. It'll show up when the **show_genres** parameter is *1*. + items: + $ref: "#/components/schemas/Genre" + type: array + podcasts: + description: Podcast suggestions. It'll show up when the **show_podcasts** parameter is 1. + items: + $ref: "#/components/schemas/PodcastTypeaheadResult" + type: array + terms: + description: Search term suggestions. + examples: + - - startup sales + - startup + - startups + - star wars + items: + type: string + type: array + required: + - terms + type: object + UpdateFrequencyHoursField: + description: How frequently does this podcast release a new episode? In hours. For example, if the value is 166, then it's every 166 hours (or weekly). + examples: + - 168 + type: integer + WebsiteField: + description: Website url of this podcast. + examples: + - http://sw7x7.com/ + type: string + iTunesIdField: + description: iTunes id for this podcast. + examples: + - 896354638 + type: integer +webhooks: + podcastDeleted: + post: + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PodcastMinimumRss" + description: Triggered by your request to DELETE /podcasts/{id}, if the podcast is actually deleted. + responses: + "200": + description: Return a 200 status to indicate that the data was received successfully + podcastsSubmitAccepted: + post: + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PodcastMinimumRss" + description: Triggered by your request to POST /podcasts/submit, if the podcast submission is accepted. + responses: + "200": + description: Return a 200 status to indicate that the data was received successfully + podcastsSubmitRejected: + post: + requestBody: + content: + application/json: + schema: + properties: + podcast: + properties: + rss: + $ref: "#/components/schemas/RssField" + type: object + type: object + description: Triggered by your request to POST /podcasts/submit, if the podcast submission is rejected. + responses: + "200": + description: Return a 200 status to indicate that the data was received successfully diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/placekit.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/placekit.yaml new file mode 100644 index 000000000..65df3b8c8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/placekit.yaml @@ -0,0 +1,649 @@ +openapi: 3.1.0 +servers: + - url: https://api.placekit.co +info: + contact: + name: API Support + url: https://api.placekit.co + description: PlaceKit OpenAPI Specifications ([repository](https://github.com/placekit/api-reference)) + termsOfService: https://placekit.io/terms + title: PlaceKit API Reference + version: 1.0.0 + x-apisguru-categories: + - location + x-origin: + - format: openapi + url: https://raw.githubusercontent.com/placekit/api-reference/main/openapi.yml + version: "3.1" + x-providerName: placekit.co +security: + - api_key: [] +paths: + /reverse: + post: + description: | + Performs a reverse geocoding search. + + It will return the closest results around `coordinates`.\ + If `coordinates` are not set, it will use the user's IP to approximate its coordinates but results will be less accurate (city level accuracy instead of street level accuracy). + operationId: reverse + requestBody: + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/parameters" + - properties: + countryByIP: + default: true + description: | + Automatically select the country to search in via the user IP's detected location.\ + Returned results will be coming from the user's country's IP.\ + If set to `true`, the parameter `countries` acts as a fallback. + type: boolean + type: object + description: Request parameters + required: false + responses: + "200": + $ref: "#/components/responses/200" + "401": + $ref: "#/components/responses/401" + "403": + $ref: "#/components/responses/403" + "404": + $ref: "#/components/responses/404" + "412": + $ref: "#/components/responses/412" + "422": + $ref: "#/components/responses/422" + "429": + $ref: "#/components/responses/429" + summary: Reverse geocoding + x-codeSamples: + - lang: curl + source: |- + curl --location --request POST 'https://api.placekit.co/reverse' \ + --header 'Content-Type: application/json' \ + --header 'x-placekit-api-key: ' \ + --data-raw '{ + "countries": ["fr"], + "language": "fr", + "types": ["street"], + "maxResults": 5, + "coordinates": "48.873662, 2.295063" + }' + - lang: go + source: |- + package main + + import ( + "fmt" + "strings" + "net/http" + "io/ioutil" + ) + + func main() { + + url := "https://api.placekit.co/reverse" + method := "POST" + + payload := strings.NewReader(`{ + "countries": ["fr"], + "language": "fr", + "types": ["street"], + "maxResults": 5, + "coordinates": "48.873662, 2.295063" + }`) + + client := &http.Client { + } + req, err := http.NewRequest(method, url, payload) + + if err != nil { + fmt.Println(err) + return + } + req.Header.Add("Content-Type", "application/json") + req.Header.Add("x-placekit-api-key", "") + + res, err := client.Do(req) + if err != nil { + fmt.Println(err) + return + } + defer res.Body.Close() + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(body)) + } + - lang: js + source: |- + var myHeaders = new Headers(); + myHeaders.append('Content-Type', 'application/json'); + myHeaders.append('x-placekit-api-key', ''); + + var raw = JSON.stringify({ + countries: ['fr'], + language: 'fr', + types: ['street'], + maxResults: 5, + coordinates: '48.873662, 2.295063' + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch('https://api.placekit.co/reverse', requestOptions) + .then(response => response.text()) + .then(result => console.log(result)) + .catch(error => console.log('error', error)); + - lang: python + source: |- + import http.client + import json + + conn = http.client.HTTPSConnection('api.placekit.co') + payload = json.dumps({ + 'countries': ['fr'], + 'language': 'fr', + 'types': ['street'], + 'maxResults': 5, + 'coordinates': '48.873662, 2.295063' + }) + headers = { + 'Content-Type': 'application/json', + 'x-placekit-api-key': '' + } + conn.request('POST', '/reverse', payload, headers) + res = conn.getresponse() + data = res.read() + print(data.decode('utf-8')) + - lang: ruby + source: | + require 'uri' + require 'json' + require 'net/http' + + url = URI('https://api.placekit.co/reverse') + + https = Net::HTTP.new(url.host, url.port) + https.use_ssl = true + + request = Net::HTTP::Post.new(url) + request['Content-Type'] = 'application/json' + request['x-placekit-api-key'] = '' + request.body = { + countries: ['fr'], + language: 'fr', + types: ['street'], + maxResults: 5, + coordinates: '48.873662, 2.295063' + }.to_json + + response = https.request(request) + pp JSON.parse(response.read_body) + x-codegen-request-body-name: payload + /search: + post: + description: | + Performs a forward geocoding search. + + It will return results around `coordinates` (if provided) and the best matching textual relevance. + + **It is highly recommended** to set the `countries` parameter with the country you need results from for the best accuracy and revelance possible. + operationId: search + requestBody: + content: + application/json: + schema: + allOf: + - properties: + query: + default: "" + description: Search query terms. + example: 42 avenue Champs Elysees Paris + type: string + type: object + - $ref: "#/components/schemas/parameters" + description: Request parameters + required: false + responses: + "200": + $ref: "#/components/responses/200" + "401": + $ref: "#/components/responses/401" + "403": + $ref: "#/components/responses/403" + "404": + $ref: "#/components/responses/404" + "412": + $ref: "#/components/responses/412" + "422": + $ref: "#/components/responses/422" + "429": + $ref: "#/components/responses/429" + summary: Search for addresses + x-codeSamples: + - lang: curl + source: |- + curl --location --request POST 'https://api.placekit.co/search' \ + --header 'Content-Type: application/json' \ + --header 'x-placekit-api-key: ' \ + --data-raw '{ + "query": "42 avenue Champs Elysees Paris", + "countries": ["fr"], + "language": "fr", + "types": ["street"], + "maxResults": 5, + "coordinates": "48.873662, 2.295063" + }' + - lang: go + source: |- + package main + + import ( + "fmt" + "strings" + "net/http" + "io/ioutil" + ) + + func main() { + + url := "https://api.placekit.co/search" + method := "POST" + + payload := strings.NewReader(`{ + "query": "42 avenue Champs Elysees Paris", + "countries": ["fr"], + "language": "fr", + "types": ["street"], + "maxResults": 5, + "coordinates": "48.873662, 2.295063" + }`) + + client := &http.Client { + } + req, err := http.NewRequest(method, url, payload) + + if err != nil { + fmt.Println(err) + return + } + req.Header.Add("Content-Type", "application/json") + req.Header.Add("x-placekit-api-key", "") + + res, err := client.Do(req) + if err != nil { + fmt.Println(err) + return + } + defer res.Body.Close() + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(body)) + } + - lang: js + source: |- + var myHeaders = new Headers(); + myHeaders.append('Content-Type', 'application/json'); + myHeaders.append('x-placekit-api-key', ''); + + var raw = JSON.stringify({ + query: '42 avenue Champs Elysees Paris', + countries: ['fr'], + language: 'fr', + types: ['street'], + maxResults: 5, + coordinates: '48.873662, 2.295063' + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch('https://api.placekit.co/search', requestOptions) + .then(response => response.text()) + .then(result => console.log(result)) + .catch(error => console.log('error', error)); + - lang: python + source: |- + import http.client + import json + + conn = http.client.HTTPSConnection('api.placekit.co') + payload = json.dumps({ + 'query': '42 avenue Champs Elysees Paris', + 'countries': ['fr'], + 'language': 'fr', + 'types': ['street'], + 'maxResults': 5, + 'coordinates': '48.873662, 2.295063' + }) + headers = { + 'Content-Type': 'application/json', + 'x-placekit-api-key': '' + } + conn.request('POST', '/search', payload, headers) + res = conn.getresponse() + data = res.read() + print(data.decode('utf-8')) + - lang: ruby + source: | + require 'uri' + require 'json' + require 'net/http' + + url = URI('https://api.placekit.co/search') + + https = Net::HTTP.new(url.host, url.port) + https.use_ssl = true + + request = Net::HTTP::Post.new(url) + request['Content-Type'] = 'application/json' + request['x-placekit-api-key'] = '' + request.body = { + query: '42 avenue Champs Elysees Paris', + countries: ['fr'], + language: 'fr', + types: ['street'], + maxResults: 5, + coordinates: '48.873662, 2.295063' + }.to_json + + response = https.request(request) + pp JSON.parse(response.read_body) + x-codegen-request-body-name: payload +components: + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/results" + description: Returns a list of matching addresses + headers: + RateLimit-Limit: + description: Request limit per minute. + example: 5 + schema: + type: integer + RateLimit-Remaining: + description: The number of requests left for the time window. + example: 2 + schema: + type: integer + RateLimit-Reset: + description: Indicates how many seconds are left to wait before making a follow-up request. + example: 34 + schema: + type: integer + Retry-After: + description: Indicates how many seconds to wait before making a follow-up request. + example: 60 + schema: + type: integer + "401": + content: + application/json: + schema: + properties: + message: + example: Access denied authentication failed + type: string + type: object + description: Access denied authentication failed + "403": + content: + application/json: + schema: + properties: + message: + example: You are not authorized to access this resource + type: string + type: object + description: You are not authorized to access this resource + "404": + content: + application/json: + schema: + properties: + message: + example: Route not found + type: string + type: object + description: Route not found + "412": + content: + application/json: + schema: + properties: + message: + example: Access denied missing credentials + type: string + type: object + description: Access denied missing credentials + "422": + content: + application/json: + schema: + properties: + errors: + example: + - location: body + msg: Must be an integer between 1 and 20 included. + param: maxResults + value: 42 + - location: body + msg: This country is not supported. Contact us if you need it. + param: countries[0] + value: sx + items: + $ref: "#/components/schemas/validationError" + type: array + message: + example: "Invalid body parameters. Check the API documentation: https://api.placekit.io/" + type: string + type: object + description: Invalid body parameters + "429": + content: + application/json: + schema: + properties: + message: + example: Too many requests from this IP, please try again in a minute + type: string + status: + example: 429 + type: integer + type: object + description: Too many requests from this IP, please try again in a minute + schemas: + entity: + properties: + administrative: + description: Administrative name (region). + example: Île-de-France + type: string + city: + description: City name. + example: Paris 8e Arrondissement + type: string + country: + description: Country name. + example: France + type: string + countrycode: + description: | + [Two-letter ISO 3166-1 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + example: fr + type: string + county: + description: County name (department). + example: Paris + type: string + highlight: + description: Name of the current entity with highlighted matched words. + example: 42 Avenue des Champs Élysées + type: string + lat: + description: Latitude. + example: 48.871086 + type: number + lng: + description: Longitude. + example: 2.3036339 + type: number + name: + description: Name of the current entity. + example: 42 Avenue des Champs Élysées + type: string + population: + description: Population number of the entity city. + example: 2220445 + type: integer + type: + description: Type of the entity. + enum: + - airport + - bus + - city + - country + - street + - tourism + - townhall + - train + example: street + type: string + zipcode: + description: Postcodes associated with the entity. + example: + - "75008" + items: + type: string + type: array + type: object + parameters: + properties: + coordinates: + description: | + GPS coordinates latitude and longitude.\ + Used to improve relevancy of results around the given area. + example: 48.873662, 2.295063 + type: string + countries: + description: | + Array of [two-letter ISO 3166-1 alpha-2 country codes](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).\ + Limit the results to given countries.\ + Select only one country for the best results. + example: + - fr + items: + type: string + type: array + countryByIP: + default: false + description: | + Automatically select the country to search in via the user IP's detected location.\ + Returned results will be coming from the user's country's IP.\ + If set to `true`, the parameter `countries` acts as a fallback. + type: boolean + language: + description: | + [Two-letter ISO 639-1 language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes).\ + Default results are in their original language.\ + By setting this parameter, you can change the language of the results, if the translation is available.\ + Contact us if you need other languages. + enum: + - en + - fr + example: fr + type: string + maxResults: + default: 5 + description: Maximum number of results to return. + maximum: 20 + minimum: 1 + type: integer + types: + description: | + Select the types of record to return.\ + Prepend with `-` to omit a type.\ + Returns all types by default. + items: + $ref: "#/components/schemas/types" + type: array + type: object + results: + properties: + maxResults: + description: Maximum number of results items returned. + example: 5 + type: integer + query: + description: Search text query used for this response. + example: 42 avenue Champs Elysees Paris + type: string + results: + items: + $ref: "#/components/schemas/entity" + type: array + resultsCount: + description: Number of items results found. + example: 2 + type: integer + type: object + types: + enum: + - airport + - -airport + - bus + - -bus + - city + - -city + - country + - -country + - street + - -street + - tourism + - -tourism + - townhall + - -townhall + - train + - -train + type: string + validationError: + properties: + location: + type: string + msg: + type: string + param: + type: string + value: + type: string + type: object + securitySchemes: + api_key: + description: Generate your API key in the [app settings](https://app.placekit.io/). + in: header + name: x-placekit-api-key + type: apiKey diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/urlbox.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/urlbox.yaml new file mode 100644 index 000000000..bb5c74c1c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/urlbox.yaml @@ -0,0 +1,255 @@ +openapi: 3.1.0 +servers: + - url: https://api.urlbox.io +info: + description: A plugin that allows the user to capture screenshots of a web page from a URL or HTML using ChatGPT. + title: Urlbox API + version: v1 + x-apisguru-categories: + - developer_tools + x-logo: + url: https://www.urlbox.io/logos/logo4.png + x-origin: + - format: openapi + url: https://www.urlbox.io/.well-known/open-api.yaml + version: "3.1" + x-providerName: urlbox.io +paths: + /v1/render/sync: + post: + operationId: renderSync + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RenderRequest" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/RenderResponse" + description: Successful operation + headers: + x-renders-allowed: + description: The number of renders allowed + schema: + type: integer + x-renders-reset: + description: The date and time when the render count will reset + schema: + type: string + x-renders-used: + description: The number of renders used + schema: + type: integer + x-urlbox-acceptedby: + description: The server that accepted the request + schema: + type: string + x-urlbox-cache-status: + description: The cache status of the response + schema: + type: string + x-urlbox-cachekey: + description: The cache key used by URLBox + schema: + type: string + x-urlbox-renderedby: + description: The server that rendered the response + schema: + type: string + x-urlbox-requestid: + description: The request ID assigned by URLBox + schema: + type: string + "307": + content: + application/json: + example: + location: https://api.urlbox.io/v1/redirect/BQxxwO98uwkSsuJf/1dca9bae-c49d-42d3-8282-89450afb7e73/1 + message: Please follow the redirect to continue your long running request + schema: + $ref: "#/components/schemas/RedirectResponse" + description: Temporary Redirect + headers: + Location: + schema: + description: The URL to follow for the long running request + format: uri + type: string + "400": + content: + application/json: + example: + error: + code: ApiKeyNotFound + message: Api Key does not exist + schema: + $ref: "#/components/schemas/ErrorResponse" + description: Bad request + headers: + x-urlbox-error-message: + description: An error message describing the reason the request failed + schema: + type: string + "401": + content: + application/json: + example: + error: + code: ApiKeyNotFound + message: Api Key does not exist + schema: + $ref: "#/components/schemas/ErrorResponse" + description: Unauthorized + headers: + x-urlbox-error-message: + description: An error message describing the reason the request failed + schema: + type: string + "500": + content: + application/json: + example: + error: + code: ApiKeyNotFound + message: Something went wrong rendering that + schema: + $ref: "#/components/schemas/ErrorResponse" + description: Internal server error + headers: + x-urlbox-error-message: + description: An error message describing the reason the request failed + schema: + type: string + security: + - SecretKey: [] + summary: Render a URL as an image or video +components: + schemas: + ErrorResponse: + properties: + error: + properties: + code: + description: A machine-readable error code + type: string + message: + description: A human-readable error message + type: string + type: object + required: + - error + type: object + RedirectResponse: + properties: + location: + description: The URL to follow for the long running request + format: uri + type: string + message: + description: A human-readable message indicating the need to follow the redirect + type: string + required: + - message + - location + type: object + RenderRequest: + oneOf: + - required: + - url + - required: + - html + properties: + block_ads: + description: Whether to block ads on the rendered page + type: boolean + click_accept: + description: Whether to automatically click accept buttons on the rendered page + type: boolean + delay: + description: The amount of milliseconds to delay before taking a screenshot + type: string + format: + description: The format of the rendered output + enum: + - png + - jpg + - pdf + - svg + - mp4 + - webp + - webm + - html + type: string + full_page: + description: Whether to capture the full page + type: boolean + gpu: + description: Whether to enable GPU rendering + type: boolean + height: + description: The viewport height of the rendered output + type: integer + hide_cookie_banners: + description: Whether to hide cookie banners on the rendered page + type: boolean + html: + description: The raw HTML to render as an image or video + type: string + metadata: + description: Whether to return metadata about the URL + type: boolean + retina: + description: Whether to render the image in retina quality + type: boolean + selector: + description: The CSS selector of an element you would like to capture + type: string + thumb_height: + description: The height of the thumbnail image + type: integer + thumb_width: + description: The width of the thumbnail image + type: integer + url: + description: The URL to render as an image or video + type: string + wait_for: + description: CSS selector of an element to wait to be present in the web page before rendering + type: string + wait_to_leave: + description: CSS selector of an element, such as a loading spinner, to wait to leave the web page before rendering + type: string + wait_until: + description: When + enum: + - requestsfinished + - mostrequestsfinished + - loaded + - domloaded + type: string + width: + description: The viewport width of the rendered output + type: integer + type: object + RenderResponse: + properties: + renderUrl: + description: The URL where the rendered output is stored + format: uri + type: string + size: + description: The size of the rendered output in bytes + format: int64 + type: integer + type: object + securitySchemes: + SecretKey: + bearerFormat: JWT + description: | + The Urlbox API uses your secret API key to authenticate. To find your secret key, login to the Urlbox dashboard at https://urlbox.io/dashboard. + scheme: bearer + type: http diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/vercel.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/vercel.yaml new file mode 100644 index 000000000..d7819a2ee --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/vercel.yaml @@ -0,0 +1,23810 @@ +openapi: 3.1.0 +servers: + - description: Production API + url: https://api.vercel.com +x-hasEquivalentPaths: true +info: + contact: + email: support@vercel.com + name: Vercel Support + url: https://vercel.com/support + description: Vercel combines the best developer experience with an obsessive focus on end-user performance. Our platform enables frontend teams to do their best work. + title: Vercel API + version: 0.0.1 + x-apisguru-categories: + - hosting + x-logo: + url: https://pbs.twimg.com/profile_images/1252531684353998848/6R0-p1Vf_400x400.jpg + x-origin: + - format: openapi + url: https://openapi.vercel.sh + version: "3.0" + x-providerName: vercel.com +paths: + /registration: + post: + description: Request a new login for a user to get a token. This will respond with a verification token and send an email to confirm the request. Once confirmed you can use the verification token to get an authentication token. + operationId: emailLogin + parameters: [] + requestBody: + content: + application/json: + schema: + properties: + email: + description: The user email. + examples: + - user@mail.com + type: string + tokenName: + description: The desired name for the token. It will be displayed on the user account details. + examples: + - Your Client App Name + type: string + required: + - email + type: object + responses: + "200": + content: + application/json: + schema: + properties: + securityCode: + description: The code the user is going to receive on the email. **Must** be displayed to the user so they can verify the request is the correct. + examples: + - Practical Saola + type: string + token: + description: The token used to verify the user accepted the login request + examples: + - T1dmvPu36nmyYisXAs7IRzcR + type: string + required: + - token + - securityCode + type: object + description: The request was successful and an email was sent + "400": + description: |- + One of the provided values in the request body is invalid. + The provided email is invalid because the owner is blocked + security: [] + summary: Login with email + tags: + - authentication + /registration/verify: + get: + description: Verify the user accepted the login request and get a authentication token. The user email address and the token received after requesting the login must be added to the URL as a query string with the names `email` and `token`. + operationId: verifyToken + parameters: + - description: Email to verify the login. + in: query + name: email + required: false + schema: + description: Email to verify the login. + type: string + - description: The token returned when the login was requested. + in: query + name: token + required: true + schema: + description: The token returned when the login was requested. + type: string + - description: The desired name for the token. It will be displayed on the user account details. + in: query + name: tokenName + required: false + schema: + description: The desired name for the token. It will be displayed on the user account details. + examples: + - Your Client App Name + type: string + - description: The SAML Profile ID, when connecting a SAML Profile to a Team member for the first time. + in: query + name: ssoUserId + required: false + schema: + description: The SAML Profile ID, when connecting a SAML Profile to a Team member for the first time. + type: string + responses: + "200": + content: + application/json: + schema: + properties: + email: + description: Email address of the authenticated user. + examples: + - amy@example.com + type: string + teamId: + description: When completing SAML Single Sign-On authentication, this will be the ID of the Team that was authenticated for. + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + token: + description: The user authentication token that can be used to perform API requests. + examples: + - 1ioXyz9Ue4xdCYGROet1dlKd + type: string + required: + - token + - email + type: object + description: The verification was successful. + "400": + description: |- + One of the provided values in the request query is invalid. + The provided token exists but is not yet confirmed + "403": + description: |- + You do not have permission to access this resource. + The verification sso token is invalid or not found + The verification token is invalid or not found + "404": + description: "" + security: [] + summary: Verify a login request to get an authentication token + tags: + - authentication + "/v1/deployments/{deploymentId}/checks": + get: + description: List all of the checks created for a deployment. + operationId: getAllChecks + parameters: + - description: The deployment to get all checks for + in: path + name: deploymentId + required: true + schema: + description: The deployment to get all checks for + examples: + - dpl_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + checks: + items: + properties: + completedAt: + type: number + conclusion: + enum: + - canceled + - failed + - neutral + - succeeded + - skipped + - stale + type: string + createdAt: + type: number + detailsUrl: + type: string + id: + type: string + integrationId: + type: string + name: + type: string + output: + properties: + metrics: + properties: + CLS: + properties: + previousValue: + type: number + source: + enum: + - web-vitals + type: string + value: + type: + - number + - "null" + required: + - value + - source + type: object + FCP: + properties: + previousValue: + type: number + source: + enum: + - web-vitals + type: string + value: + type: + - number + - "null" + required: + - value + - source + type: object + LCP: + properties: + previousValue: + type: number + source: + enum: + - web-vitals + type: string + value: + type: + - number + - "null" + required: + - value + - source + type: object + TBT: + properties: + previousValue: + type: number + source: + enum: + - web-vitals + type: string + value: + type: + - number + - "null" + required: + - value + - source + type: object + virtualExperienceScore: + properties: + previousValue: + type: number + source: + enum: + - web-vitals + type: string + value: + type: + - number + - "null" + required: + - value + - source + type: object + required: + - FCP + - LCP + - CLS + - TBT + type: object + type: object + path: + type: string + rerequestable: + type: boolean + startedAt: + type: number + status: + enum: + - registered + - running + - completed + type: string + updatedAt: + type: number + required: + - createdAt + - id + - integrationId + - name + - rerequestable + - status + - updatedAt + type: object + type: array + required: + - checks + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: Retrieve a list of all checks + tags: + - checks + post: + description: Creates a new check. This endpoint must be called with an OAuth2 or it will produce a 400 error. + operationId: createCheck + parameters: + - description: The deployment to create the check for. + in: path + name: deploymentId + required: true + schema: + description: The deployment to create the check for. + examples: + - dpl_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + blocking: + description: Whether the check should block a deployment from succeeding + examples: + - true + type: boolean + detailsUrl: + description: URL to display for further details + examples: + - http://example.com + type: string + externalId: + description: An identifier that can be used as an external reference + examples: + - 1234abc + type: string + name: + description: The name of the check being created + examples: + - Performance Check + maxLength: 100 + type: string + path: + description: Path of the page that is being checked + examples: + - / + maxLength: 255 + type: string + rerequestable: + description: Whether a user should be able to request for the check to be rerun if it fails + examples: + - true + type: boolean + required: + - name + - blocking + type: object + responses: + "200": + content: + application/json: + schema: + description: Information for the SAML Single Sign-On configuration. + properties: + connectedAt: + description: Timestamp (in milliseconds) of when the configuration was connected. + examples: + - 1611796915677 + type: number + lastReceivedWebhookEvent: + description: Timestamp (in milliseconds) of when the last webhook event was received from WorkOS. + examples: + - 1611796915677 + type: number + state: + description: Current state of the connection. + examples: + - active + type: string + status: + description: Current status of the connection. + examples: + - linked + type: string + type: + description: The Identity Provider "type", for example Okta. + examples: + - OktaSAML + type: string + required: + - type + - status + - state + - connectedAt + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + Cannot create check for finished deployment + The provided token is not from an OAuth2 Client + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: Creates a new Check + tags: + - checks + "/v1/deployments/{deploymentId}/checks/{checkId}": + get: + description: Return a detailed response for a single check. + operationId: getCheck + parameters: + - description: The deployment to get the check for. + in: path + name: deploymentId + required: true + schema: + description: The deployment to get the check for. + examples: + - dpl_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The check to fetch + in: path + name: checkId + required: true + schema: + description: The check to fetch + examples: + - check_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: From T, pick a set of properties whose keys are in the union K + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - creator + - domain + - id + - name + - recordType + - type + - value + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: |- + You do not have permission to access this resource. + The provided token is not from an OAuth2 Client that created the Check + "404": + description: |- + Check was not found + The deployment was not found + security: + - bearerToken: [] + summary: Get a single check + tags: + - checks + patch: + description: Update an existing check. This endpoint must be called with an OAuth2 or it will produce a 400 error. + operationId: updateCheck + parameters: + - description: The deployment to update the check for. + in: path + name: deploymentId + required: true + schema: + description: The deployment to update the check for. + examples: + - dpl_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The check being updated + in: path + name: checkId + required: true + schema: + description: The check being updated + examples: + - check_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + conclusion: + description: The result of the check being run + enum: + - canceled + - failed + - neutral + - succeeded + - skipped + detailsUrl: + description: A URL a user may visit to see more information about the check + examples: + - https://example.com/check/run/1234abc + type: string + externalId: + description: An identifier that can be used as an external reference + examples: + - 1234abc + type: string + name: + description: The name of the check being created + examples: + - Performance Check + maxLength: 100 + type: string + output: + description: The results of the check Run + properties: + metrics: + additionalProperties: false + description: Metrics about the page + properties: + CLS: + properties: + previousValue: + description: Previous Cumulative Layout Shift value to display a delta + examples: + - 2 + type: number + source: + enum: + - web-vitals + type: string + value: + description: Cumulative Layout Shift value + examples: + - 4 + type: + - number + - "null" + required: + - value + - source + type: object + FCP: + properties: + previousValue: + description: Previous First Contentful Paint value to display a delta + examples: + - 900 + type: number + source: + enum: + - web-vitals + type: string + value: + description: First Contentful Paint value + examples: + - 1200 + type: + - number + - "null" + required: + - value + - source + type: object + LCP: + properties: + previousValue: + description: Previous Largest Contentful Paint value to display a delta + examples: + - 1000 + type: number + source: + enum: + - web-vitals + type: string + value: + description: Largest Contentful Paint value + examples: + - 1200 + type: + - number + - "null" + required: + - value + - source + type: object + TBT: + properties: + previousValue: + description: Previous Total Blocking Time value to display a delta + examples: + - 3500 + type: number + source: + enum: + - web-vitals + value: + description: Total Blocking Time value + examples: + - 3000 + type: + - number + - "null" + required: + - value + - source + type: object + virtualExperienceScore: + properties: + previousValue: + description: A previous Virtual Experience Score value to display a delta, between 0 and 100 + examples: + - 35 + maximum: 100 + minimum: 0 + type: integer + source: + enum: + - web-vitals + value: + description: The calculated Virtual Experience Score value, between 0 and 100 + examples: + - 30 + maximum: 100 + minimum: 0 + type: + - integer + - "null" + required: + - value + - source + type: object + required: + - FCP + - LCP + - CLS + - TBT + type: object + type: object + path: + description: Path of the page that is being checked + examples: + - / + maxLength: 255 + type: string + status: + description: The current status of the check + enum: + - running + - completed + type: object + responses: + "200": + content: + application/json: + schema: + description: Information for the SAML Single Sign-On configuration. + properties: + connectedAt: + description: Timestamp (in milliseconds) of when the configuration was connected. + examples: + - 1611796915677 + type: number + lastReceivedWebhookEvent: + description: Timestamp (in milliseconds) of when the last webhook event was received from WorkOS. + examples: + - 1611796915677 + type: number + state: + description: Current state of the connection. + examples: + - active + type: string + status: + description: Current status of the connection. + examples: + - linked + type: string + type: + description: The Identity Provider "type", for example Okta. + examples: + - OktaSAML + type: string + required: + - type + - status + - state + - connectedAt + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The provided token is not from an OAuth2 Client + "403": + description: You do not have permission to access this resource. + "404": + description: |- + Check was not found + The deployment was not found + "413": + description: The output provided is too large + security: + - bearerToken: [] + summary: Update a check + tags: + - checks + "/v1/deployments/{deploymentId}/checks/{checkId}/rerequest": + post: + description: Rerequest a selected check that has failed. + operationId: rerequestCheck + parameters: + - description: The deployment to rerun the check for. + in: path + name: deploymentId + required: true + schema: + description: The deployment to rerun the check for. + examples: + - dpl_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The check to rerun + in: path + name: checkId + required: true + schema: + description: The check to rerun + examples: + - check_2qn7PZrx89yxY34vEZPD31Y9XVj6 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + The deployment was not found + Check was not found + security: + - bearerToken: [] + summary: Rerequest a check + tags: + - checks + "/v1/domains/records/{recordId}": + patch: + description: Updates an existing DNS record for a domain name. + operationId: updateRecord + parameters: + - description: The id of the DNS record + in: path + name: recordId + required: true + schema: + description: The id of the DNS record + examples: + - rec_2qn7pzrx89yxy34vezpd31y9 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + additionalProperties: false + mxPriority: + description: The MX priority value of the DNS record + type: + - integer + - "null" + name: + description: The name of the DNS record + examples: + - example-1 + type: + - string + - "null" + srv: + additionalProperties: false + properties: + port: + description: "" + type: + - integer + - "null" + priority: + description: "" + type: + - integer + - "null" + target: + description: "" + examples: + - example2.com. + maxLength: 255 + type: + - string + - "null" + weight: + description: "" + type: + - integer + - "null" + required: + - target + - weight + - port + - priority + type: + - object + - "null" + ttl: + description: The Time to live (TTL) value of the DNS record + examples: + - "60" + maximum: 2147483647 + minimum: 60 + type: + - integer + - "null" + type: + description: The type of the DNS record + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + examples: + - A + maxLength: 255 + type: + - string + - "null" + value: + description: The value of the DNS record + examples: + - google.com + type: + - string + - "null" + type: object + responses: + "200": + content: + application/json: + schema: + description: From T, pick a set of properties whose keys are in the union K + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - creator + - domain + - id + - name + - recordType + - type + - value + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "401": + description: "" + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Update an existing DNS record + tags: + - dns + /v1/edge-config: + get: + description: Returns all Edge Configs. + operationId: getEdgeConfigs + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: List of all edge configs. + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + itemCount: + type: number + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + sizeInBytes: + type: number + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - sizeInBytes + - itemCount + type: object + description: List of all edge configs. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get Edge Configs + tags: + - edge-config + post: + description: Creates an Edge Config. + operationId: createEdgeConfig + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + items: + additionalProperties: + oneOf: + - oneOf: + - type: string + - type: number + - type: boolean + - type: "null" + - type: object + - items: + oneOf: + - type: string + - type: number + - type: boolean + - type: "null" + - type: object + type: array + propertyNames: + maxLength: 256 + pattern: ^[\\w-]+$ + type: string + type: object + slug: + maxLength: 32 + pattern: ^[\\w-]+$ + type: string + required: + - slug + type: object + responses: + "201": + content: + application/json: + schema: + description: An Edge Config + properties: + connectedAt: + description: Timestamp (in milliseconds) of when the configuration was connected. + examples: + - 1611796915677 + type: number + itemCount: + type: number + lastReceivedWebhookEvent: + description: Timestamp (in milliseconds) of when the last webhook event was received from WorkOS. + examples: + - 1611796915677 + type: number + sizeInBytes: + type: number + state: + description: Current state of the connection. + examples: + - active + type: string + status: + description: Current status of the connection. + examples: + - linked + type: string + type: + description: The Identity Provider "type", for example Okta. + examples: + - OktaSAML + type: string + required: + - sizeInBytes + - itemCount + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Create an Edge Config + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}": + delete: + description: Delete an Edge Config by id. + operationId: deleteEdgeConfig + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: "" + "400": + description: One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Delete an Edge Config + tags: + - edge-config + get: + description: Returns an Edge Config. + operationId: getEdgeConfig + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: The EdgeConfig. + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + itemCount: + type: number + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + sizeInBytes: + type: number + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - sizeInBytes + - itemCount + type: object + description: The EdgeConfig. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get an Edge Config + tags: + - edge-config + put: + description: Updates an Edge Config. + operationId: updateEdgeConfig + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + slug: + maxLength: 32 + pattern: ^[\\w-]+$ + type: string + required: + - slug + type: object + responses: + "200": + content: + application/json: + schema: + description: An Edge Config + properties: + connectedAt: + description: Timestamp (in milliseconds) of when the configuration was connected. + examples: + - 1611796915677 + type: number + itemCount: + type: number + lastReceivedWebhookEvent: + description: Timestamp (in milliseconds) of when the last webhook event was received from WorkOS. + examples: + - 1611796915677 + type: number + sizeInBytes: + type: number + state: + description: Current state of the connection. + examples: + - active + type: string + status: + description: Current status of the connection. + examples: + - linked + type: string + type: + description: The Identity Provider "type", for example Okta. + examples: + - OktaSAML + type: string + required: + - sizeInBytes + - itemCount + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Update an Edge Config + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}/item/{edgeConfigItemKey}": + get: + description: Returns a specific Edge Config Item. + operationId: getEdgeConfigItem + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - in: path + name: edgeConfigItemKey + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EdgeConfigItem" + description: The EdgeConfig. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get an Edge Config item + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}/items": + get: + description: Returns all items of an Edge Config. + operationId: getEdgeConfigItems + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EdgeConfigItem" + description: The EdgeConfig. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get Edge Config items + tags: + - edge-config + patch: + description: Update multiple Edge Config Items in batch. + operationId: patchtEdgeConfigItems + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + items: + items: + oneOf: + - properties: + key: + maxLength: 256 + pattern: ^[\\w-]+$ + type: string + operation: + oneOf: + - const: create + - const: update + - const: upsert + value: + oneOf: + - oneOf: + - type: string + - type: number + - type: boolean + - type: "null" + - type: object + - items: + oneOf: + - type: string + - type: number + - type: boolean + - type: "null" + - type: object + type: array + required: + - operation + - key + - value + type: object + - properties: + key: + maxLength: 256 + pattern: ^[\\w-]+$ + type: string + operation: + const: delete + required: + - operation + - key + type: object + type: array + required: + - items + type: object + responses: + "200": + content: + application/json: + schema: + properties: + status: + type: string + required: + - status + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Update Edge Config items in batch + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}/token": + post: + description: Adds a token to an existing Edge Config. + operationId: createEdgeConfigToken + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + label: + maxLength: 52 + type: string + required: + - label + type: object + responses: + "201": + content: + application/json: + schema: + properties: + id: + type: string + token: + type: string + required: + - token + - id + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Create an Edge Config token + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}/token/{token}": + get: + description: Return meta data about an Edge Config token. + operationId: getEdgeConfigToken + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - in: path + name: token + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EdgeConfigToken" + description: The EdgeConfig. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get Edge Config token meta data + tags: + - edge-config + "/v1/edge-config/{edgeConfigId}/tokens": + delete: + description: Deletes one or more tokens of an existing Edge Config. + operationId: deleteEdgeConfigTokens + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + tokens: + items: + type: string + type: array + required: + - tokens + type: object + responses: + "204": + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Delete one or more Edge Config tokens + tags: + - edge-config + get: + description: Returns all tokens of an Edge Config. + operationId: getEdgeConfigTokens + parameters: + - in: path + name: edgeConfigId + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EdgeConfigToken" + description: The EdgeConfig. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get all tokens of an Edge Config + tags: + - edge-config + "/v1/integrations/configuration/{id}": + delete: + description: Allows to remove the configuration with the `id` provided in the parameters. The configuration and all of its resources will be removed. This includes Webhooks, LogDrains and Project Env variables. + operationId: deleteConfiguration + parameters: + - in: path + name: id + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: The configuration was successfully removed + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The configuration was not found + security: + - bearerToken: [] + summary: Delete an integration configuration + tags: + - integrations + get: + description: Allows to retrieve a the configuration with the provided id in case it exists. The authenticated user or team must be the owner of the config in order to access it. + operationId: getConfiguration + parameters: + - description: ID of the configuration to check + in: path + name: id + required: true + schema: + description: ID of the configuration to check + examples: + - icfg_cuwj0AdCdH3BwWT4LPijCC7t + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - description: Make all properties in T optional + properties: + completedAt: + description: A timestamp that tells you when the configuration was installed successfully + examples: + - 1558531915505 + type: number + createdAt: + description: A timestamp that tells you when the configuration was created + examples: + - 1558531915505 + type: number + deletedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: + - number + - "null" + disabledAt: + description: "A timestamp that tells you when the configuration was disabled. Note: Configurations can be disabled when the associated user loses access to a team. They do not function during this time until the configuration is 'transferred', meaning the associated user is changed to one with access to the team." + examples: + - 1558531915505 + type: number + id: + description: The unique identifier of the configuration + examples: + - icfg_3bwCLgxL8qt5kjRLcv2Dit7F + type: string + integrationId: + description: The unique identifier of the app the configuration was created for + examples: + - oac_xzpVzcUOgcB1nrVlirtKhbWV + type: string + oauthConfiguration: + description: Will be truthy in those cases where the configuration was created to authorize a client through the OAuth2 flow. + examples: + - false + type: boolean + ownerId: + description: The user or team ID that owns the configuration + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projects: + description: When a configuration is limited to access certain projects, this will contain each of the project ID it is allowed to access. If it is not defined, the configuration has full access. + examples: + - - prj_xQxbutw1HpL6HLYPAzt5h75m8NjO + items: + type: string + type: array + removedLogDrainsAt: + type: number + removedProjectEnvsAt: + type: number + removedTokensAt: + type: number + removedWebhooksAt: + type: number + scopes: + description: The resources that are allowed to be accessed by the configuration. + examples: + - - read:project + - read-write:log-drain + items: + type: string + type: array + scopesQueue: + items: + properties: + confirmedAt: + type: number + note: + type: string + requestedAt: + type: number + scopes: + properties: + added: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + upgraded: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + required: + - added + - upgraded + type: object + required: + - scopes + - note + - requestedAt + type: object + type: array + slug: + description: The slug of the integration the configuration is created for. + examples: + - slack + type: string + source: + description: Source defines where the configuration was installed from. It is used to analyze user engagement for integration installations in product metrics. + enum: + - marketplace + - deploy-button + - oauth + - external + examples: + - marketplace + type: string + teamId: + description: When the configuration was created for a team, this will show the ID of the team. + examples: + - team_nLlpyC6RE1qxydlFKbrxDlud + type: + - string + - "null" + type: + enum: + - integration-configuration + type: string + updatedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: number + userId: + description: The ID of the user that created the configuration. + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + required: + - createdAt + - id + - integrationId + - ownerId + - slug + - type + - updatedAt + - userId + - scopes + type: object + - properties: + canConfigureOpenTelemetry: + type: boolean + completedAt: + description: A timestamp that tells you when the configuration was installed successfully + examples: + - 1558531915505 + type: number + createdAt: + description: A timestamp that tells you when the configuration was created + examples: + - 1558531915505 + type: number + disabledAt: + description: "A timestamp that tells you when the configuration was disabled. Note: Configurations can be disabled when the associated user loses access to a team. They do not function during this time until the configuration is 'transferred', meaning the associated user is changed to one with access to the team." + examples: + - 1558531915505 + type: number + id: + description: The unique identifier of the configuration + examples: + - icfg_3bwCLgxL8qt5kjRLcv2Dit7F + type: string + integrationId: + description: The unique identifier of the app the configuration was created for + examples: + - oac_xzpVzcUOgcB1nrVlirtKhbWV + type: string + oauthConfiguration: + description: Will be truthy in those cases where the configuration was created to authorize a client through the OAuth2 flow. + examples: + - false + type: boolean + ownerId: + description: The user or team ID that owns the configuration + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projectSelection: + description: A string representing the permission for projects. Possible values are `all` or `selected`. + enum: + - selected + - all + examples: + - all + type: string + projects: + description: When a configuration is limited to access certain projects, this will contain each of the project ID it is allowed to access. If it is not defined, the configuration has full access. + examples: + - - prj_xQxbutw1HpL6HLYPAzt5h75m8NjO + items: + type: string + type: array + scopes: + description: The resources that are allowed to be accessed by the configuration. + examples: + - - read:project + - read-write:log-drain + items: + type: string + type: array + slug: + description: The slug of the integration the configuration is created for. + examples: + - slack + type: string + source: + description: Source defines where the configuration was installed from. It is used to analyze user engagement for integration installations in product metrics. + enum: + - marketplace + - deploy-button + - oauth + - external + examples: + - marketplace + type: string + teamId: + description: When the configuration was created for a team, this will show the ID of the team. + examples: + - team_nLlpyC6RE1qxydlFKbrxDlud + type: + - string + - "null" + updatedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: number + userId: + description: The ID of the user that created the configuration. + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + required: + - projectSelection + - createdAt + - id + - integrationId + - ownerId + - slug + - updatedAt + - userId + - scopes + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The configuration was not found + security: + - bearerToken: [] + summary: Retrieve an integration configuration + tags: + - integrations + /v1/integrations/configurations: + get: + description: Allows to retrieve all configurations for an authenticated integration. When the `project` view is used, configurations generated for the authorization flow will be filtered out of the results. + operationId: getConfigurations + parameters: + - in: query + name: view + required: true + schema: + enum: + - account + - project + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - items: + description: Make all properties in T optional + properties: + completedAt: + description: A timestamp that tells you when the configuration was installed successfully + examples: + - 1558531915505 + type: number + createdAt: + description: A timestamp that tells you when the configuration was created + examples: + - 1558531915505 + type: number + deletedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: + - number + - "null" + disabledAt: + description: "A timestamp that tells you when the configuration was disabled. Note: Configurations can be disabled when the associated user loses access to a team. They do not function during this time until the configuration is 'transferred', meaning the associated user is changed to one with access to the team." + examples: + - 1558531915505 + type: number + id: + description: The unique identifier of the configuration + examples: + - icfg_3bwCLgxL8qt5kjRLcv2Dit7F + type: string + integrationId: + description: The unique identifier of the app the configuration was created for + examples: + - oac_xzpVzcUOgcB1nrVlirtKhbWV + type: string + oauthConfiguration: + description: Will be truthy in those cases where the configuration was created to authorize a client through the OAuth2 flow. + examples: + - false + type: boolean + ownerId: + description: The user or team ID that owns the configuration + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projects: + description: When a configuration is limited to access certain projects, this will contain each of the project ID it is allowed to access. If it is not defined, the configuration has full access. + examples: + - - prj_xQxbutw1HpL6HLYPAzt5h75m8NjO + items: + type: string + type: array + removedLogDrainsAt: + type: number + removedProjectEnvsAt: + type: number + removedTokensAt: + type: number + removedWebhooksAt: + type: number + scopes: + description: The resources that are allowed to be accessed by the configuration. + examples: + - - read:project + - read-write:log-drain + items: + type: string + type: array + scopesQueue: + items: + properties: + confirmedAt: + type: number + note: + type: string + requestedAt: + type: number + scopes: + properties: + added: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + upgraded: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + required: + - added + - upgraded + type: object + required: + - scopes + - note + - requestedAt + type: object + type: array + slug: + description: The slug of the integration the configuration is created for. + examples: + - slack + type: string + source: + description: Source defines where the configuration was installed from. It is used to analyze user engagement for integration installations in product metrics. + enum: + - marketplace + - deploy-button + - oauth + - external + examples: + - marketplace + type: string + teamId: + description: When the configuration was created for a team, this will show the ID of the team. + examples: + - team_nLlpyC6RE1qxydlFKbrxDlud + type: + - string + - "null" + type: + enum: + - integration-configuration + type: string + updatedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: number + userId: + description: The ID of the user that created the configuration. + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + required: + - createdAt + - id + - integrationId + - ownerId + - slug + - type + - updatedAt + - userId + - scopes + type: object + type: array + - items: + properties: + completedAt: + description: A timestamp that tells you when the configuration was installed successfully + examples: + - 1558531915505 + type: number + createdAt: + description: A timestamp that tells you when the configuration was created + examples: + - 1558531915505 + type: number + deletedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: + - number + - "null" + disabledAt: + description: "A timestamp that tells you when the configuration was disabled. Note: Configurations can be disabled when the associated user loses access to a team. They do not function during this time until the configuration is 'transferred', meaning the associated user is changed to one with access to the team." + examples: + - 1558531915505 + type: number + id: + description: The unique identifier of the configuration + examples: + - icfg_3bwCLgxL8qt5kjRLcv2Dit7F + type: string + integration: + properties: + assignedBetaLabelAt: + type: number + category: + type: string + flags: + items: + type: string + type: array + icon: + type: string + isLegacy: + type: boolean + name: + type: string + required: + - name + - icon + - category + - isLegacy + type: object + integrationId: + description: The unique identifier of the app the configuration was created for + examples: + - oac_xzpVzcUOgcB1nrVlirtKhbWV + type: string + oauthConfiguration: + description: Will be truthy in those cases where the configuration was created to authorize a client through the OAuth2 flow. + examples: + - false + type: boolean + ownerId: + description: The user or team ID that owns the configuration + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projects: + description: When a configuration is limited to access certain projects, this will contain each of the project ID it is allowed to access. If it is not defined, the configuration has full access. + examples: + - - prj_xQxbutw1HpL6HLYPAzt5h75m8NjO + items: + type: string + type: array + removedLogDrainsAt: + type: number + removedProjectEnvsAt: + type: number + removedTokensAt: + type: number + removedWebhooksAt: + type: number + scopes: + description: The resources that are allowed to be accessed by the configuration. + examples: + - - read:project + - read-write:log-drain + items: + type: string + type: array + scopesQueue: + items: + properties: + confirmedAt: + type: number + note: + type: string + requestedAt: + type: number + scopes: + properties: + added: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + upgraded: + items: + enum: + - read:integration-configuration + - read-write:integration-configuration + - read:deployment + - read-write:deployment + - read-write:deployment-check + - read:project + - read-write:project + - read-write:project-env-vars + - read-write:global-project-env-vars + - read:team + - read:user + - read-write:log-drain + - read:domain + - read-write:domain + - read-write:edge-config + - read-write:otel-endpoint + - read:monitoring + type: string + type: array + required: + - added + - upgraded + type: object + required: + - scopes + - note + - requestedAt + type: object + type: array + slug: + description: The slug of the integration the configuration is created for. + examples: + - slack + type: string + source: + description: Source defines where the configuration was installed from. It is used to analyze user engagement for integration installations in product metrics. + enum: + - marketplace + - deploy-button + - oauth + - external + examples: + - marketplace + type: string + teamId: + description: When the configuration was created for a team, this will show the ID of the team. + examples: + - team_nLlpyC6RE1qxydlFKbrxDlud + type: + - string + - "null" + type: + enum: + - integration-configuration + type: string + updatedAt: + description: A timestamp that tells you when the configuration was updated. + examples: + - 1558531915505 + type: number + userId: + description: The ID of the user that created the configuration. + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + required: + - integration + - createdAt + - id + - integrationId + - ownerId + - slug + - type + - updatedAt + - userId + - scopes + type: object + type: array + description: The list of configurations for the authenticated user + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get configurations for the authenticated user or team + tags: + - integrations + /v1/integrations/git-namespaces: + get: + description: Lists git namespaces for a supported provider. Supported providers are `github`, `gitlab` and `bitbucket`. If the provider is not provided, it will try to obtain it from the user that authenticated the request. + operationId: gitNamespaces + parameters: + - in: query + name: provider + schema: + enum: + - github + - gitlab + - bitbucket + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + properties: + id: + oneOf: + - type: string + - type: number + name: + type: string + ownerType: + type: string + provider: + type: string + slug: + type: string + required: + - provider + - slug + - id + - ownerType + type: object + type: array + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List git namespaces by provider + tags: + - integrations + "/v1/integrations/log-drains/{id}": + delete: + description: Deletes the Integration log drain with the provided `id`. When using an OAuth2 Token, the log drain can be deleted only if the integration owns it. + operationId: deleteIntegrationLogDrain + parameters: + - description: ID of the log drain to be deleted + in: path + name: id + required: true + schema: + description: ID of the log drain to be deleted + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: The log drain was successfully deleted + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The log drain was not found + security: + - bearerToken: [] + summary: Deletes the Integration log drain with the provided `id` + tags: + - logDrains + /v1/integrations/search-repo: + get: + operationId: searchRepo + description: Lists git repositories linked to a namespace `id` for a supported provider. A specific namespace `id` can be obtained via the `git-namespaces` endpoint. Supported providers are `github`, `gitlab` and `bitbucket`. If the provider or namespace is not provided, it will try to obtain it from the user that authenticated the request. + parameters: + - in: query + name: query + schema: + type: string + - in: query + name: namespaceId + schema: + type: + - string + - number + - "null" + - in: query + name: provider + schema: + enum: + - github + - gitlab + - bitbucket + - in: query + name: installationId + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + gitAccount: + properties: + namespaceId: + oneOf: + - type: string + - type: number + type: "null" + provider: + enum: + - github + - gitlab + - bitbucket + type: string + required: + - provider + - namespaceId + type: object + repos: + items: + properties: + defaultBranch: + type: string + id: + oneOf: + - type: string + - type: number + name: + type: string + namespace: + type: string + ownerType: + enum: + - team + - user + type: string + private: + type: boolean + slug: + type: string + updatedAt: + type: number + url: + type: string + required: + - id + - name + - slug + - namespace + - private + - defaultBranch + - url + - updatedAt + - ownerType + type: object + type: array + required: + - gitAccount + - repos + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List git repositories linked to namespace by provider + tags: + - integrations + /v1/log-drains: + get: + description: Retrieves a list of Configurable Log Drains. This endpoint must be called with a team AccessToken (integration OAuth2 clients are not allowed). Only log drains owned by the authenticated team can be accessed. + operationId: getConfigurableLogDrains + parameters: + - in: query + name: projectId + schema: + pattern: ^[a-zA-z0-9_]+$ + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + properties: + branch: + description: The branch to filter logs by + examples: + - main + type: string + configurationId: + description: The ID of the related integration configuration + type: string + createdAt: + description: A number containing the date when the log-drain was created in in milliseconds + examples: + - 1567024758130 + type: number + deliveryFormat: + description: The log-drain defined delivery format + enum: + - json + - ndjson + - syslog + examples: + - - json + - ndjson + type: string + environment: + description: The environment to filter logs by + enum: + - preview + - production + examples: + - production + type: string + headers: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + examples: + - foo: bar + type: object + id: + description: The log-drain id + examples: + - ld_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the deployment belongs to + examples: + - team_ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the deployment is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + sources: + description: The log-drain defined sources + examples: + - - lambda + - build + items: + description: The log-drain defined sources + enum: + - static + - lambda + - build + - edge + - external + - deployment + examples: + - - lambda + - build + type: string + type: array + url: + description: A string with the URL of the log-drain + examples: + - https://my-log-drain.com + type: string + required: + - createdAt + - id + - ownerId + - deliveryFormat + - url + type: object + type: array + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Retrieves a list of Configurable Log Drains + tags: + - logDrains + post: + description: Creates a configurable log drain. This endpoint must be called with a team AccessToken (integration OAuth2 clients are not allowed) + operationId: createConfigurableLogDrain + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + branch: + description: The branch regexp of log drain + examples: + - feature/* + type: string + deliveryFormat: + description: The delivery log format + enum: + - json + - ndjson + examples: + - json + environment: + description: The environment of log drain + enum: + - preview + - production + examples: + - production + headers: + additionalProperties: + type: string + description: Headers to be sent together with the request + type: object + projectIds: + items: + pattern: ^[a-zA-z0-9_]+$ + type: string + maxItems: 50 + minItems: 1 + type: array + sources: + items: + enum: + - static + - lambda + - build + - edge + - external + type: string + minItems: 1 + type: array + uniqueItems: true + url: + description: The log drain url + format: uri + pattern: ^(http|https)?:// + type: string + required: + - deliveryFormat + - url + - sources + type: object + responses: + "200": + content: + application/json: + schema: + properties: + branch: + description: The branch to filter logs by + examples: + - main + type: string + configurationId: + description: The ID of the related integration configuration + type: string + createdAt: + description: A number containing the date when the log-drain was created in in milliseconds + examples: + - 1567024758130 + type: number + deliveryFormat: + description: The log-drain defined delivery format + enum: + - json + - ndjson + - syslog + examples: + - - json + - ndjson + type: string + environment: + description: The environment to filter logs by + enum: + - preview + - production + examples: + - production + type: string + headers: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + examples: + - foo: bar + type: object + id: + description: The log-drain id + examples: + - ld_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the deployment belongs to + examples: + - team_ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the deployment is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + secret: + description: The secret to validate the log-drain payload + type: string + sources: + description: The log-drain defined sources + examples: + - - lambda + - build + items: + description: The log-drain defined sources + enum: + - static + - lambda + - build + - edge + - external + - deployment + examples: + - - lambda + - build + type: string + type: array + url: + description: A string with the URL of the log-drain + examples: + - https://my-log-drain.com + type: string + required: + - createdAt + - id + - ownerId + - deliveryFormat + - url + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Creates a Configurable Log Drain + tags: + - logDrains + "/v1/log-drains/{id}": + delete: + description: Deletes a Configurable Log Drain. This endpoint must be called with a team AccessToken (integration OAuth2 clients are not allowed). Only log drains owned by the authenticated team can be deleted. + operationId: deleteConfigurableLogDrain + parameters: + - in: path + name: id + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Deletes a Configurable Log Drain + tags: + - logDrains + get: + description: Retrieves a Configurable Log Drain. This endpoint must be called with a team AccessToken (integration OAuth2 clients are not allowed). Only log drains owned by the authenticated team can be accessed. + operationId: getConfigurableLogDrain + parameters: + - in: path + name: id + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + branch: + description: The branch to filter logs by + examples: + - main + type: string + configurationId: + description: The ID of the related integration configuration + type: string + createdAt: + description: A number containing the date when the log-drain was created in in milliseconds + examples: + - 1567024758130 + type: number + deliveryFormat: + description: The log-drain defined delivery format + enum: + - json + - ndjson + - syslog + examples: + - - json + - ndjson + type: string + environment: + description: The environment to filter logs by + enum: + - preview + - production + examples: + - production + type: string + headers: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + examples: + - foo: bar + type: object + id: + description: The log-drain id + examples: + - ld_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the deployment belongs to + examples: + - team_ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the deployment is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + sources: + description: The log-drain defined sources + examples: + - - lambda + - build + items: + description: The log-drain defined sources + enum: + - static + - lambda + - build + - edge + - external + - deployment + examples: + - - lambda + - build + type: string + type: array + url: + description: A string with the URL of the log-drain + examples: + - https://my-log-drain.com + type: string + required: + - createdAt + - id + - ownerId + - deliveryFormat + - url + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Retrieves a Configurable Log Drain + tags: + - logDrains + "/v1/projects/{idOrName}/env/{id}": + get: + description: Retrieve the environment variable for a given project. + operationId: getProjectEnv + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_XLKmu1DyR1eY7zq8UgeRKbA7yVLA + type: string + - description: The unique ID for the environment variable to get the decrypted value. + in: path + name: id + required: true + schema: + description: The unique ID for the environment variable to get the decrypted value. + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The project could not be found + security: + - bearerToken: [] + summary: Retrieve the decrypted value of an environment variable of a project by id + tags: + - projects + /v1/teams: + post: + description: Create a new Team under your account. You need to send a POST request with the desired Team slug, and optionally the Team name. + operationId: createTeam + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + name: + description: The desired name for the Team. It will be generated from the provided slug if nothing is provided + examples: + - A Random Team + maxLength: 256 + type: string + slug: + description: The desired slug for the Team + examples: + - a-random-team + maxLength: 48 + type: string + required: + - slug + type: object + responses: + "200": + content: + application/json: + schema: + description: The team was created successfuly + properties: + id: + description: Id of the created team + examples: + - team_nLlpyC6RE1qxqglFKbrMxlud + type: string + required: + - id + type: object + description: The team was created successfuly + "400": + description: |- + One of the provided values in the request body is invalid. + The slug is already in use + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Create a Team + tags: + - teams + "/v1/teams/{teamId}": + delete: + description: Delete a team under your account. You need to send a `DELETE` request with the desired team `id`. An optional array of reasons for deletion may also be sent. + operationId: deleteTeam + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + reasons: + description: Optional array of objects that describe the reason why the team is being deleted. + items: + additionalProperties: false + description: An object describing the reason why the team is being deleted. + properties: + description: + description: Description of the reason why the team is being deleted. + type: string + slug: + description: Idenitifier slug of the reason why the team is being deleted. + type: string + required: + - slug + - description + type: object + type: array + type: object + responses: + "200": + content: + application/json: + schema: + description: The Team was successfuly deleted + properties: + id: + description: The ID of the deleted Team + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + required: + - id + type: object + description: The Team was successfuly deleted + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: "" + "403": + description: |- + You do not have permission to access this resource. + The authenticated user can't access the team + "404": + description: The team was not found + security: + - bearerToken: [] + summary: Delete a Team + tags: + - teams + "/v1/teams/{teamId}/invites/{inviteId}": + delete: + description: Delete an active Team invite code. + operationId: deleteTeamInviteCode + parameters: + - description: The Team invite code ID. + in: path + name: inviteId + required: true + schema: + description: The Team invite code ID. + examples: + - 2wn2hudbr4chb1ecywo9dvzo7g9sscs6mzcz8htdde0txyom4l + type: string + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + id: + description: ID of the team. + type: string + required: + - id + type: object + description: Successfully deleted Team invite code. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: |- + You do not have permission to access this resource. + Invite managed by directory sync + Not authorized to access this team. + "404": + description: |- + Team invite code not found. + No team found. + security: + - bearerToken: [] + summary: Delete a Team invite code + tags: + - teams + "/v1/teams/{teamId}/members": + post: + description: Invite a user to join the team specified in the URL. The authenticated user needs to be an `OWNER` in order to successfully invoke this endpoint. The user can be specified with an email or an ID. If both email and ID are provided, ID will take priority. + operationId: inviteUserToTeam + parameters: + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + email: + description: The email address of the user to invite + examples: + - john@example.com + format: email + type: string + role: {} + uid: + description: The id of the user to invite + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + type: object + responses: + "200": + content: + application/json: + schema: + oneOf: + - description: The member was successfully added to the team + properties: + email: + description: The email of the invited user. Not included if the user was invited via their UID. + examples: + - john@user.co + type: string + role: + description: The role used for the invitation + examples: + - MEMBER + type: string + uid: + description: The ID of the invited user + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + username: + description: The username of the invited user + examples: + - john-doe + type: string + required: + - uid + - username + - email + - role + type: object + - properties: + role: + type: string + uid: + type: string + username: + type: string + required: + - uid + - username + - role + type: object + description: The member was successfully added to the team + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The user is already a team member + The user already requested access to the team + Hobby teams are not allowed to add seats. + The team reached the maximum allowed amount of members + "403": + description: |- + You do not have permission to access this resource. + The authenticated user must be a team owner to perform the action + "404": + description: The team was not found + security: + - bearerToken: [] + summary: Invite a user + tags: + - teams + "/v1/teams/{teamId}/members/teams/join": + post: + description: Join a team with a provided invite code or team ID. + operationId: joinTeam + parameters: + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + inviteCode: + description: The invite code to join the team. + examples: + - fisdh38aejkeivn34nslfore9vjtn4ls + type: string + teamId: + description: The team ID. + examples: + - team_3oNwMKqLHqEBh02CTPsrbNbe + type: string + type: object + responses: + "200": + content: + application/json: + schema: + description: Successfully joined a team. + properties: + from: + description: The origin of how the user joined. + examples: + - email + type: string + name: + description: The name of the team the user joined. + examples: + - My Team + type: string + slug: + description: The slug of the team the user joined. + examples: + - my-team + type: string + teamId: + description: The ID of the team the user joined. + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + required: + - teamId + - slug + - name + - from + type: object + description: Successfully joined a team. + "400": + description: |- + One of the provided values in the request body is invalid. + Reached the max. amount of team members. + "401": + description: "" + "402": + description: "" + "403": + description: You do not have permission to access this resource. + "404": + description: Team not found. + security: + - bearerToken: [] + summary: Join a team + tags: + - teams + "/v1/teams/{teamId}/members/{uid}": + delete: + description: Remove a Team Member from the Team, or dismiss a user that requested access, or leave a team. + operationId: removeTeamMember + parameters: + - description: The user ID of the member. + in: path + name: uid + required: true + schema: + description: The user ID of the member. + examples: + - ndlgr43fadlPyCtREAqxxdyFK + type: string + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + id: + description: ID of the team. + type: string + required: + - id + type: object + description: Successfully removed a member of the team. + "400": + description: |- + One of the provided values in the request query is invalid. + Cannot leave the team as the only owner. + "403": + description: |- + You do not have permission to access this resource. + Not authorized to update the team. + "404": + description: |- + A user with the specified ID does not exist. + No team found. + security: + - bearerToken: [] + summary: Remove a Team Member + tags: + - teams + patch: + description: Update the membership of a Team Member on the Team specified by `teamId`, such as changing the _role_ of the member, or confirming a request to join the Team for an unconfirmed member. The authenticated user must be an `OWNER` of the Team. + operationId: updateTeamMember + parameters: + - description: The ID of the member. + in: path + name: uid + required: true + schema: + description: The ID of the member. + examples: + - ndfasllgPyCtREAqxxdyFKb + type: string + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + confirmed: + description: Accept a user who requested access to the team. + enum: + - true + examples: + - true + type: boolean + joinedFrom: + additionalProperties: false + properties: + ssoUserId: + type: "null" + type: object + role: + default: + - MEMBER + - VIEWER + description: The role in the team of the member. + examples: + - - MEMBER + - VIEWER + type: string + type: object + responses: + "200": + content: + application/json: + schema: + properties: + id: + description: ID of the team. + type: string + required: + - id + type: object + description: Successfully updated the membership. + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + Cannot disconnect SSO from a Team member that does not have a SSO connection. + Cannot confirm a member that is already confirmed. + Cannot confirm a member that did not request access. + "401": + description: Team members can only be updated by an owner, or by the authenticated user if they are only disconnecting their SAML connection to the Team. + "402": + description: "" + "403": + description: You do not have permission to access this resource. + "404": + description: |- + The provided user is not part of this team. + A user with the specified ID does not exist. + Team not found. + security: + - bearerToken: [] + summary: Update a Team Member + tags: + - teams + "/v1/teams/{teamId}/request": + post: + description: Request access to a team as a member. An owner has to approve the request. Only 10 users can request access to a team at the same time. + operationId: requestAccessToTeam + parameters: + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + joinedFrom: + additionalProperties: false + properties: + commitId: + description: The commit sha if the origin is a git provider. + examples: + - f498d25d8bd654b578716203be73084b31130cd7 + type: string + gitUserId: + description: The ID of the Git account of the user who requests access. + examples: + - 103053343 + oneOf: + - type: string + - type: number + gitUserLogin: + description: The login name for the Git account of the user who requests access. + examples: + - jane-doe + type: string + origin: + description: The origin of the request. + enum: + - import + - teams + - github + - gitlab + - bitbucket + - feedback + - organization-teams + examples: + - github + type: string + repoId: + description: The ID of the repository for the given Git provider. + examples: + - "67753070" + type: string + repoPath: + description: The path to the repository for the given Git provider. + examples: + - jane-doe/example + type: string + required: + - origin + type: object + required: + - joinedFrom + type: object + responses: + "200": + content: + application/json: + schema: + properties: + accessRequestedAt: + type: number + bitbucket: + properties: + login: + type: string + type: + - object + - "null" + confirmed: + type: boolean + github: + properties: + login: + type: string + type: + - object + - "null" + gitlab: + properties: + login: + type: string + type: + - object + - "null" + joinedFrom: + properties: + commitId: + type: string + dsyncConnectedAt: + type: number + dsyncUserId: + type: string + gitUserId: + oneOf: + - type: string + - type: number + gitUserLogin: + type: string + idpUserId: + type: string + origin: + enum: + - import + - teams + - github + - gitlab + - bitbucket + - feedback + - organization-teams + - mail + - link + - saml + - dsync + type: string + repoId: + type: string + repoPath: + type: string + ssoConnectedAt: + type: number + ssoUserId: + type: string + required: + - origin + type: object + teamName: + type: string + teamSlug: + type: string + required: + - teamSlug + - teamName + - github + - gitlab + - bitbucket + type: object + description: Successfuly requested access to the team. + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "401": + description: "" + "403": + description: You do not have permission to access this resource. + "404": + description: The team was not found. + security: + - bearerToken: [] + summary: Request access to a team + tags: + - teams + "/v1/teams/{teamId}/request/{userId}": + get: + description: Check the status of a join request. It'll respond with a 404 if the request has been declined. If no `userId` path segment was provided, this endpoint will instead return the status of the authenticated user. + operationId: getTeamAccessRequest + parameters: + - in: path + name: userId + required: true + schema: + type: string + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + accessRequestedAt: + description: Timestamp in milliseconds when the user requested access to the team. + examples: + - 1588720733602 + type: number + bitbucket: + description: Map of the connected Bitbucket account. + properties: + login: + type: string + type: + - object + - "null" + confirmed: + description: Current status of the membership. Will be `true` if confirmed, if pending it'll be `false`. + examples: + - false + type: boolean + github: + description: Map of the connected GitHub account. + properties: + login: + type: string + type: + - object + - "null" + gitlab: + description: Map of the connected GitLab account. + properties: + login: + type: string + type: + - object + - "null" + joinedFrom: + description: A map that describes the origin from where the user joined. + properties: + commitId: + type: string + dsyncConnectedAt: + type: number + dsyncUserId: + type: string + gitUserId: + oneOf: + - type: string + - type: number + gitUserLogin: + type: string + idpUserId: + type: string + origin: + enum: + - import + - mail + - link + - teams + - github + - gitlab + - bitbucket + - saml + - dsync + - feedback + - organization-teams + type: string + repoId: + type: string + repoPath: + type: string + ssoConnectedAt: + type: number + ssoUserId: + type: string + required: + - origin + type: object + teamName: + description: The name of the team. + examples: + - My Team + type: string + teamSlug: + description: The slug of the team. + examples: + - my-team + type: string + required: + - teamSlug + - teamName + - confirmed + - joinedFrom + - accessRequestedAt + - github + - gitlab + - bitbucket + type: object + description: Successfully + "400": + description: |- + One of the provided values in the request query is invalid. + User is already a confirmed member of the team and did not request access. Only visible when the authenticated user does have access to the team. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + The provided user doesn't have a membership. + Team was not found. + security: + - bearerToken: [] + summary: Get access request status + tags: + - teams + /v1/user: + delete: + description: Initiates the deletion process for the currently authenticated User, by sending a deletion confirmation email. The email contains a link that the user needs to visit in order to proceed with the deletion process. + operationId: requestDelete + parameters: [] + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + reasons: + description: Optional array of objects that describe the reason why the User account is being deleted. + items: + additionalProperties: false + description: An object describing the reason why the User account is being deleted. + properties: + description: + description: Description of the reason why the User account is being deleted. + type: string + slug: + description: Idenitifier slug of the reason why the User account is being deleted. + type: string + required: + - slug + - description + type: object + type: array + type: object + responses: + "202": + content: + application/json: + schema: + properties: + email: + description: Email address of the User who has initiated deletion. + type: string + id: + description: Unique identifier of the User who has initiated deletion. + type: string + message: + description: User deletion progress status. + examples: + - Verification email sent + type: string + required: + - id + - email + - message + type: object + description: Response indicating that the User deletion process has been initiated, and a confirmation email has been sent. + "400": + description: One of the provided values in the request body is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Delete User Account + tags: + - user + /v1/webhooks: + get: + description: Get a list of webhooks + operationId: getWebhooks + parameters: + - in: query + name: projectId + schema: + pattern: ^[a-zA-z0-9_]+$ + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - items: + properties: + createdAt: + description: A number containing the date when the webhook was created in in milliseconds + examples: + - 1567024758130 + type: number + events: + description: The webhooks events + examples: + - deployment.created + items: + description: The webhooks events + enum: + - domain.created + - deployment.created + - deployment.error + - deployment.canceled + - deployment.succeeded + - deployment.ready + - deployment.check-rerequested + - integration-configuration.permission-upgraded + - integration-configuration.removed + - integration-configuration.scope-change-confirmed + - project.created + - project.removed + - deployment-checks-completed + - deployment-ready + - deployment-prepared + - deployment-error + - deployment-check-rerequested + - deployment-canceled + - project-created + - project-removed + - domain-created + - deployment + - integration-configuration-permission-updated + - integration-configuration-removed + - integration-configuration-scope-change-confirmed + examples: + - deployment.created + type: string + type: array + id: + description: The webhook id + examples: + - account_hook_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the webhook belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the webhook is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + projectsMetadata: + items: + properties: + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + id: + type: string + latestDeployment: + type: string + name: + type: string + required: + - id + - name + type: object + type: + - array + - "null" + updatedAt: + description: A number containing the date when the webhook was updated in in milliseconds + examples: + - 1567024758130 + type: number + url: + description: A string with the URL of the webhook + examples: + - https://my-webhook.com + type: string + required: + - projectsMetadata + - events + - id + - url + - ownerId + - createdAt + - updatedAt + type: object + type: array + - items: + properties: + createdAt: + description: A number containing the date when the webhook was created in in milliseconds + examples: + - 1567024758130 + type: number + events: + description: The webhooks events + examples: + - deployment.created + items: + description: The webhooks events + enum: + - domain.created + - deployment.created + - deployment.error + - deployment.canceled + - deployment.succeeded + - deployment.ready + - deployment.check-rerequested + - integration-configuration.permission-upgraded + - integration-configuration.removed + - integration-configuration.scope-change-confirmed + - project.created + - project.removed + - deployment-checks-completed + - deployment-ready + - deployment-prepared + - deployment-error + - deployment-check-rerequested + - deployment-canceled + - project-created + - project-removed + - domain-created + - deployment + - integration-configuration-permission-updated + - integration-configuration-removed + - integration-configuration-scope-change-confirmed + examples: + - deployment.created + type: string + type: array + id: + description: The webhook id + examples: + - account_hook_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the webhook belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the webhook is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + updatedAt: + description: A number containing the date when the webhook was updated in in milliseconds + examples: + - 1567024758130 + type: number + url: + description: A string with the URL of the webhook + examples: + - https://my-webhook.com + type: string + required: + - events + - id + - url + - ownerId + - createdAt + - updatedAt + type: object + type: array + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get a list of webhooks + tags: + - webhooks + post: + description: Creates a webhook + operationId: createWebhook + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + events: + items: + enum: + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DomainCreate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentCreate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentErro + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentCancele + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentSucceede + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentRead + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.DeploymentCheckRerequeste + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.IntegrationConfigurationPermissionUpgrade + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.IntegrationConfigurationRemove + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.IntegrationConfigurationScopeChangeConfirme + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.ProjectCreate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.ProjectRemove + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentChecksComplete + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentRead + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentPrepare + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentErro + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentCheckRerequeste + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymentCancele + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyProjectCreate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyProjectRemove + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDomainCreate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyDeploymen + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyIntegrationConfigurationPermissionUpdate + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyIntegrationConfigurationRemove + - mport("/vercel/path0/utils/webhooks/webhooks/types").WebhookName.LegacyIntegrationConfigurationScopeChangeConfirme + type: string + minItems: 1 + type: array + projectIds: + items: + pattern: ^[a-zA-z0-9_]+$ + type: string + maxItems: 50 + minItems: 1 + type: array + url: + format: uri + pattern: ^https?:// + type: string + required: + - url + - events + type: object + responses: + "200": + content: + application/json: + schema: + properties: + createdAt: + description: A number containing the date when the webhook was created in in milliseconds + examples: + - 1567024758130 + type: number + events: + description: The webhooks events + examples: + - deployment.created + items: + description: The webhooks events + enum: + - domain.created + - deployment.created + - deployment.error + - deployment.canceled + - deployment.succeeded + - deployment.ready + - deployment.check-rerequested + - integration-configuration.permission-upgraded + - integration-configuration.removed + - integration-configuration.scope-change-confirmed + - project.created + - project.removed + - deployment-checks-completed + - deployment-ready + - deployment-prepared + - deployment-error + - deployment-check-rerequested + - deployment-canceled + - project-created + - project-removed + - domain-created + - deployment + - integration-configuration-permission-updated + - integration-configuration-removed + - integration-configuration-scope-change-confirmed + examples: + - deployment.created + type: string + type: array + id: + description: The webhook id + examples: + - account_hook_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the webhook belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the webhook is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + secret: + description: The webhook secret used to sign the payload + type: string + updatedAt: + description: A number containing the date when the webhook was updated in in milliseconds + examples: + - 1567024758130 + type: number + url: + description: A string with the URL of the webhook + examples: + - https://my-webhook.com + type: string + required: + - secret + - events + - id + - url + - ownerId + - createdAt + - updatedAt + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Creates a webhook + tags: + - webhooks + "/v1/webhooks/{id}": + delete: + description: Deletes a webhook + operationId: deleteWebhook + parameters: + - in: path + name: id + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Deletes a webhook + tags: + - webhooks + get: + description: Get a webhook + operationId: getWebhook + parameters: + - in: path + name: id + required: true + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + createdAt: + description: A number containing the date when the webhook was created in in milliseconds + examples: + - 1567024758130 + type: number + events: + description: The webhooks events + examples: + - deployment.created + items: + description: The webhooks events + enum: + - domain.created + - deployment.created + - deployment.error + - deployment.canceled + - deployment.succeeded + - deployment.ready + - deployment.check-rerequested + - integration-configuration.permission-upgraded + - integration-configuration.removed + - integration-configuration.scope-change-confirmed + - project.created + - project.removed + - deployment-checks-completed + - deployment-ready + - deployment-prepared + - deployment-error + - deployment-check-rerequested + - deployment-canceled + - project-created + - project-removed + - domain-created + - deployment + - integration-configuration-permission-updated + - integration-configuration-removed + - integration-configuration-scope-change-confirmed + examples: + - deployment.created + type: string + type: array + id: + description: The webhook id + examples: + - account_hook_GflD6EYyo7F4ViYS + type: string + ownerId: + description: The unique ID of the team the webhook belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + projectIds: + description: The ID of the projects the webhook is associated with + examples: + - - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + items: + type: string + type: array + updatedAt: + description: A number containing the date when the webhook was updated in in milliseconds + examples: + - 1567024758130 + type: number + url: + description: A string with the URL of the webhook + examples: + - https://my-webhook.com + type: string + required: + - events + - id + - url + - ownerId + - createdAt + - updatedAt + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get a webhook + tags: + - webhooks + "/v10/projects/{idOrName}/domains": + post: + description: Add a domain to the project by passing its domain name and by specifying the project by either passing the project `id` or `name` in the URL. If the domain is not yet verified to be used on this project, the request will return `verified = false`, and the domain will need to be verified according to the `verification` challenge via `POST /projects/:idOrName/domains/:domain/verify`. If the domain already exists on the project, the request will fail with a `400` status code. + operationId: addProjectDomain + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + gitBranch: + description: Git branch to link the project domain + examples: + - null + maxLength: 250 + type: + - string + - "null" + name: + description: The project domain name + examples: + - www.example.com + type: string + redirect: + description: Target destination domain for redirect + examples: + - foobar.com + type: + - string + - "null" + redirectStatusCode: + description: Status code for domain redirect + enum: + - null + - 301 + - 302 + - 307 + - 308 + examples: + - 307 + type: + - integer + - "null" + required: + - name + type: object + responses: + "200": + content: + application/json: + schema: + properties: + apexName: + type: string + createdAt: + type: number + gitBranch: + type: + - string + - "null" + name: + type: string + projectId: + type: string + redirect: + type: + - string + - "null" + redirectStatusCode: + enum: + - 307 + - 301 + - 302 + - 308 + type: + - number + - "null" + updatedAt: + type: number + verification: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + items: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + properties: + domain: + type: string + reason: + type: string + type: + type: string + value: + type: string + required: + - type + - domain + - value + - reason + type: object + type: array + verified: + description: "`true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed." + type: boolean + required: + - name + - apexName + - projectId + - verified + type: object + description: The domain was successfully added to the project + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The domain is not valid + You can't set both a git branch and a redirect for the domain + The domain can not be added because the latest production deployment for the project was not successful + The domain redirect is not valid + A domain cannot redirect to itself + You can not set the production branch as a branch for your domain + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + You do not have permission to access this resource. + You don't have access to the domain you are adding + "404": + description: Project not found + "409": + description: |- + The domain is already assigned to another Vercel project + Cannot create project domain since owner already has `domain` on their account + Cannot create project domain if the current verified domain + The project is currently being transferred + security: + - bearerToken: [] + summary: Add a domain to a project + tags: + - projects + "/v10/projects/{idOrName}/env": + post: + description: Create one ore more environment variables for a project by passing its `key`, `value`, `type` and `target` and by specifying the project by either passing the project `id` or `name` in the URL. + operationId: createProjectEnv + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_XLKmu1DyR1eY7zq8UgeRKbA7yVLA + type: string + - description: Allow override of environment variable if it already exists + in: query + name: upsert + required: false + schema: + description: Allow override of environment variable if it already exists + examples: + - "true" + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + oneOf: + - properties: + gitBranch: + description: The git branch of the environment variable + examples: + - feature-1 + maxLength: 250 + type: + - string + - "null" + key: + description: The name of the environment variable + examples: + - API_URL + type: string + target: + description: The target environment of the environment variable + examples: + - - production + - preview + items: + enum: + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Productio + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Previe + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Developmen + type: array + type: + description: The type of environment variable + enum: + - system + - secret + - encrypted + - plain + - sensitive + examples: + - plain + type: string + value: + description: The value of the environment variable + examples: + - https://api.vercel.com + type: string + required: + - key + - value + - type + - target + type: object + - items: + properties: + gitBranch: + description: The git branch of the environment variable + examples: + - feature-1 + maxLength: 250 + type: + - string + - "null" + key: + description: The name of the environment variable + examples: + - API_URL + type: string + target: + description: The target environment of the environment variable + examples: + - - production + - preview + items: + enum: + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Productio + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Previe + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Developmen + type: array + type: + description: The type of environment variable + enum: + - system + - secret + - encrypted + - plain + - sensitive + examples: + - plain + type: string + value: + description: The value of the environment variable + examples: + - https://api.vercel.com + type: string + required: + - key + - value + - type + - target + type: object + type: array + responses: + "201": + content: + application/json: + schema: + properties: + created: + oneOf: + - properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + type: object + - items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + type: object + type: array + failed: + items: + properties: + error: + properties: + action: + type: string + code: + type: string + envVarId: + type: string + envVarKey: + type: string + gitBranch: + type: string + key: + type: string + link: + type: string + message: + type: string + project: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + value: + oneOf: + - type: string + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + required: + - code + - message + type: object + required: + - error + type: object + type: array + required: + - created + - failed + type: object + description: The environment variable was created successfully + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + You do not have permission to access this resource. + The environment variable cannot be created because it already exists + Additional permissions are required to create production environment variables + "404": + description: The project could not be found + "409": + description: The project is being transfered and creating an environment variable is not possible + security: + - bearerToken: [] + summary: Create one or more environment variables + tags: + - projects + "/v11/deployments/{deploymentId}/builds": + get: + description: Retrieves the list of builds given their deployment's unique identifier. + operationId: listDeploymentBuilds + parameters: + - description: The deployment unique identifier + in: path + name: deploymentId + required: true + schema: + description: The deployment unique identifier + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + builds: + items: + description: An object representing a Build on Vercel + properties: + config: + description: An object that contains the Build's configuration + examples: + - zeroConfig: true + properties: + distDir: + type: string + forceBuildIn: + type: string + reuseWorkPathFrom: + type: string + zeroConfig: + type: boolean + type: object + copiedFrom: + type: string + createdAt: + description: The time at which the Build was created + examples: + - 1567071524208 + type: number + createdIn: + description: The region where the Build was first created + examples: + - sfo1 + type: string + deployedAt: + description: The time at which the Build was deployed + examples: + - 1567071598563 + type: number + deploymentId: + description: The unique identifier of the deployment + examples: + - dpl_BRGyoU2Jzzwx7myBnqv3xjRDD2GnHTwUWyFybnrUvjDD + type: string + entrypoint: + description: The entrypoint of the deployment + examples: + - api/index.js + type: string + fingerprint: + description: If the Build uses the `@vercel/static` Runtime, it contains a hashed string of all outputs + examples: + - null + type: + - string + - "null" + id: + description: The unique identifier of the Build + examples: + - bld_q5fj68jh7eewfe8 + type: string + output: + description: A list of outputs for the Build that can be either Serverless Functions or static files + items: + description: A list of outputs for the Build that can be either Serverless Functions or static files + properties: + digest: + description: The SHA1 of the file + type: string + edge: + description: Exists if the output is an edge function. + properties: + regions: + description: "The regions where the edge function will be invoked. Only exists if the edge function as a regional edge function, see: https://vercel.com/docs/concepts/edge-network/regions#setting-edge-function-regions" + items: + type: string + type: + - array + - "null" + required: + - regions + type: + - object + - "null" + lambda: + description: If the output is a Serverless Function, an object containing the name, location and memory size of the function + properties: + deployedTo: + items: + type: string + type: array + functionName: + type: string + layers: + items: + type: string + type: array + memorySize: + type: number + timeout: + type: number + required: + - functionName + - deployedTo + type: + - object + - "null" + mode: + description: The POSIX file permissions + type: number + path: + description: The absolute path of the file or Serverless Function + type: string + size: + description: The size of the file in bytes + type: number + type: + description: The type of the output + enum: + - lambda + - file + - edge + type: string + required: + - path + - digest + - mode + type: object + type: array + readyState: + description: The state of the deployment depending on the process of deploying, or if it is ready or in an error state + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + - UPLOADING + - DEPLOYING + - ARCHIVED + examples: + - READY + type: string + readyStateAt: + description: The time at which the Build state was last modified + examples: + - 1567024758130 + type: number + scheduledAt: + description: The time at which the Build was scheduled to be built + examples: + - 1567024756543 + type: + - number + - "null" + use: + description: The Runtime the Build used to generate the output + examples: + - "@vercel/node" + type: string + required: + - id + - deploymentId + - entrypoint + - readyState + - output + type: object + type: array + required: + - builds + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Deployment was not found + security: + - bearerToken: [] + summary: List Deployment Builds + tags: + - deployments + "/v12/deployments/{id}/cancel": + patch: + description: This endpoint allows you to cancel a deployment which is currently building, by supplying its `id` in the URL. + operationId: cancelDeployment + parameters: + - description: The unique identifier of the deployment. + in: path + name: id + required: true + schema: + description: The unique identifier of the deployment. + examples: + - dpl_5WJWYSyB7BpgTj3EuwF37WMRBXBtPQ2iTMJHJBJyRfd + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + alias: + description: A list of all the aliases (default aliases, staging aliases and production aliases) that were assigned upon deployment creation + examples: + - [] + items: + type: string + type: array + aliasAssigned: + description: A boolean that will be true when the aliases from the alias property were assigned successfully + examples: + - true + type: boolean + aliasAssignedAt: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + description: An object that will contain a `code` and a `message` when the aliasing fails, otherwise the value will be `null` + examples: + - null + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + aliasWarning: + properties: + action: + type: string + code: + type: string + link: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + automaticAliases: + items: + type: string + type: array + bootedAt: + type: number + build: + properties: + env: + description: The keys of the environment variables that were assigned during the build phase. + examples: + - - MY_ENV_VAR + items: + type: string + type: array + required: + - env + type: object + buildErrorAt: + type: number + buildingAt: + type: number + builds: + items: + properties: + config: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + src: + type: string + use: + type: string + required: + - use + type: object + type: array + canceledAt: + type: number + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + description: The ID of Vercel Connect configuration used for this deployment + type: string + createdAt: + description: A number containing the date when the deployment was created in milliseconds + examples: + - 1540257589405 + type: number + createdIn: + description: The region where the deployment was first created + examples: + - sfo1 + type: string + creator: + description: Information about the deployment creator + properties: + uid: + description: The ID of the user that created the deployment + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: The username of the user that created the deployment + examples: + - john-doe + type: string + required: + - uid + type: object + env: + description: The keys of the environment variables that were assigned during runtime + examples: + - - MY_SECRET + items: + type: string + type: array + errorCode: + type: string + errorLink: + type: string + errorMessage: + type: + - string + - "null" + errorStep: + type: string + functions: + additionalProperties: + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + properties: + excludeFiles: + type: string + includeFiles: + type: string + maxDuration: + type: number + memory: + type: number + runtime: + type: string + type: object + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + type: + - object + - "null" + gitRepo: + oneOf: + - properties: + defaultBranch: + type: string + name: + type: string + namespace: + type: string + ownerType: + enum: + - user + - team + type: string + path: + type: string + private: + type: boolean + projectId: + type: number + type: + enum: + - gitlab + type: string + url: + type: string + required: + - namespace + - projectId + - type + - url + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + org: + type: string + ownerType: + enum: + - user + - team + type: string + path: + type: string + private: + type: boolean + repo: + type: string + repoId: + type: number + repoOwnerId: + type: string + type: + enum: + - github + type: string + required: + - org + - repo + - repoId + - type + - repoOwnerId + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + owner: + type: string + ownerType: + enum: + - user + - team + type: string + path: + type: string + private: + type: boolean + repoUuid: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - owner + - repoUuid + - slug + - type + - workspaceUuid + - path + - defaultBranch + - name + - private + - ownerType + type: object + type: "null" + gitSource: + oneOf: + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoId: + oneOf: + - type: string + - type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - repoId + type: object + - properties: + org: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repo: + type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - org + - repo + type: object + - properties: + prId: + type: + - number + - "null" + projectId: + oneOf: + - type: string + - type: number + ref: + type: + - string + - "null" + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - projectId + type: object + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoUuid: + type: string + sha: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - repoUuid + type: object + - properties: + owner: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + required: + - type + - owner + - slug + type: object + - properties: + gitUrl: + type: string + ref: + type: string + sha: + type: string + type: + enum: + - custom + type: string + required: + - type + - ref + - sha + - gitUrl + type: object + - properties: + org: + type: string + ref: + type: string + repo: + type: string + repoId: + type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - sha + - repoId + type: object + - properties: + projectId: + type: number + ref: + type: string + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - ref + - sha + - projectId + type: object + - properties: + owner: + type: string + ref: + type: string + repoUuid: + type: string + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - ref + - sha + - workspaceUuid + - repoUuid + type: object + id: + description: A string holding the unique ID of the deployment + examples: + - dpl_89qyp1cskzkLrVicDaZoDbjyHuDJ + type: string + inspectorUrl: + description: Vercel URL to inspect the deployment. + examples: + - https://vercel.com/acme/nextjs/J1hXN00qjUeoYfpEEf7dnDtpSiVq + type: + - string + - "null" + isInConcurrentBuildsQueue: + description: Is the deployment currently queued waiting for a Concurrent Build Slot to be available + examples: + - false + type: boolean + lambdas: + items: + properties: + createdAt: + type: number + entrypoint: + type: + - string + - "null" + id: + type: string + output: + items: + properties: + functionName: + type: string + path: + type: string + required: + - path + - functionName + type: object + type: array + readyState: + enum: + - INITIALIZING + - BUILDING + - READY + - ERROR + type: string + readyStateAt: + type: number + required: + - id + - output + type: object + type: array + meta: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + monorepoManager: + description: An monorepo manager that was used for the deployment + examples: + - turbo + type: + - string + - "null" + name: + description: The name of the project associated with the deployment at the time that the deployment was created + examples: + - my-project + type: string + ownerId: + description: The unique ID of the user or team the deployment belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + plan: + description: The pricing plan the deployment was made under + enum: + - hobby + - enterprise + - pro + - oss + examples: + - pro + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + projectId: + description: The ID of the project the deployment is associated with + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + public: + description: A boolean representing if the deployment is public or not. By default this is `false` + examples: + - false + type: boolean + readyState: + description: The state of the deployment depending on the process of deploying, or if it is ready or in an error state + enum: + - INITIALIZING + - BUILDING + - READY + - ERROR + - QUEUED + - CANCELED + examples: + - READY + type: string + regions: + description: The regions the deployment exists in + examples: + - - sfo1 + items: + type: string + type: array + routes: + description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + items: + oneOf: + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + caseSensitive: + type: boolean + check: + type: boolean + continue: + type: boolean + dest: + type: string + has: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + headers: + additionalProperties: + type: string + type: object + important: + type: boolean + locale: + properties: + cookie: + type: string + redirect: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + type: object + methods: + items: + type: string + type: array + middleware: + description: A middleware index in the `middleware` key under the build result + type: number + middlewarePath: + description: A middleware key within the `output` key under the build result. Overrides a `middleware` definition. + type: string + middlewareRawSrc: + description: The original middleware matchers. + items: + type: string + type: array + missing: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + override: + type: boolean + src: + type: string + status: + type: number + required: + - src + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + dest: + type: string + handle: + enum: + - filesystem + - hit + - miss + - rewrite + - error + - resource + type: string + src: + type: string + status: + type: number + required: + - handle + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + continue: + type: boolean + middleware: + enum: + - 0 + type: number + src: + type: string + required: + - src + - continue + - middleware + type: object + type: + - array + - "null" + source: + description: Where was the deployment created from + enum: + - cli + - git + - import + - import/repo + - clone/repo + examples: + - cli + type: string + target: + description: If defined, either `staging` if a staging alias in the format `..now.sh` was assigned upon creation, or `production` if the aliases from `alias` were assigned + enum: + - staging + - production + examples: + - null + type: + - string + - "null" + team: + description: The team that owns the deployment if any + properties: + id: + description: The ID of the team owner + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + name: + description: The name of the team owner + examples: + - FSociety + type: string + slug: + description: The slug of the team owner + examples: + - fsociety + type: string + required: + - id + - name + - slug + type: object + type: + enum: + - LAMBDAS + type: string + url: + description: A string with the unique URL of the deployment + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + userAliases: + description: An array of domains that were provided by the user when creating the Deployment. + examples: + - - sub1.example.com + - sub2.example.com + items: + type: string + type: array + version: + description: The platform version that was used to create the deployment. + enum: + - 2 + examples: + - 2 + type: number + required: + - build + - createdIn + - env + - inspectorUrl + - isInConcurrentBuildsQueue + - meta + - name + - ownerId + - plan + - projectId + - routes + - alias + - aliasAssigned + - bootedAt + - buildingAt + - createdAt + - creator + - id + - public + - readyState + - regions + - type + - url + - version + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Cancel a deployment + tags: + - deployments + /v13/deployments: + post: + description: Create a new deployment with all the required and intended data. If the deployment is not a git deployment, all files must be provided with the request, either referenced or inlined. Additionally, a deployment id can be specified to redeploy a previous deployment. + operationId: createDeployment + parameters: + - description: Forces a new deployment even if there is a previous similar deployment + in: query + name: forceNew + schema: + description: Forces a new deployment even if there is a previous similar deployment + enum: + - "0" + - "1" + - description: Allows to skip framework detection so the API would not fail to ask for confirmation + in: query + name: skipAutoDetectionConfirmation + schema: + description: Allows to skip framework detection so the API would not fail to ask for confirmation + enum: + - "0" + - "1" + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + $schema: + description: Ignored. Can be set to get completions, validations and documentation in some editors. + examples: + - - https://openapi.vercel.sh/vercel.json + type: string + alias: + description: Aliases that will get assigned when the deployment is `READY` and the target is `production`. The client needs to make a `GET` request to its API to ensure the assignment + examples: + - - example.vercel.app + items: + maxLength: 253 + type: string + maxItems: 50 + maxLength: 253 + type: array + build: + additionalProperties: false + deprecated: true + description: An object containing another object with information to be passed to the Build Process + properties: + env: + additionalProperties: + maxLength: 65536 + type: string + deprecated: true + description: An object containing the deployment's environment variable names and values to be passed to Builds. Secrets can be referenced by prefixing the value with `@` + examples: + - A_SECRET: "@a-secret" + maxProperties: 100 + minProperties: 0 + type: object + type: object + buildCommand: + description: The build command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + builds: + deprecated: true + description: A list of build descriptions whose src references valid source files. + items: + additionalProperties: false + properties: + config: + description: Optionally, an object including arbitrary metadata to be passed to the Builder + type: object + src: + description: A glob expression or pathname. If more than one file is resolved, one build will be created per matched file. It can include `*` and `**` + maxLength: 4096 + type: string + use: + description: "An npm module to be installed by the build process. It can include a semver compatible version (e.g.: `@org/proj@1`)" + maxLength: 256 + type: string + required: + - use + type: object + maxItems: 128 + minItems: 0 + type: array + cleanUrls: + description: When set to `true`, all HTML files and Serverless Functions will have their extension removed. When visiting a path that ends with the extension, a 308 response will redirect the client to the extensionless path. + type: boolean + crons: + description: An array of cron jobs that should be created for production Deployments. + items: + properties: + path: + maxLength: 512 + pattern: ^/.* + type: string + schedule: + maxLength: 256 + type: string + required: + - schedule + - path + type: object + maxItems: 20 + type: array + deploymentId: + description: An deployment id for an existing deployment to redeploy + type: string + devCommand: + description: The dev command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + env: + additionalProperties: + maxLength: 65536 + type: string + deprecated: true + description: An object containing the deployment's environment variable names and values. Secrets can be referenced by prefixing the value with `@` + examples: + - A_SECRET: "@a-secret" + maxProperties: 100 + minProperties: 0 + type: object + files: + description: A list of objects with the files to be deployed + items: + oneOf: + - additionalProperties: false + description: Used in the case you want to inline a file inside the request + properties: + data: + description: The file content, it could be either a `base64` (useful for images, etc.) of the files or the plain content for source code + type: string + encoding: + description: The file content encoding, it could be either a base64 (useful for images, etc.) of the files or the plain text for source code. + enum: + - base64 + - utf-8 + file: + description: The file name including the whole path + examples: + - folder/file.js + type: string + required: + - file + - data + title: InlinedFile + type: object + - additionalProperties: false + description: Used in the case you want to reference a file that was already uploaded + properties: + file: + description: The file path relative to the project root + examples: + - folder/file.js + type: string + sha: + description: The file contents hashed with SHA1, used to check the integrity + type: string + size: + description: The file size in bytes + type: integer + required: + - file + title: UploadedFile + type: object + type: array + framework: + description: The framework that is being used for this project. When `null` is used no framework is selected + enum: + - null + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + functions: + additionalProperties: + additionalProperties: false + properties: + excludeFiles: + description: A glob pattern to match files that should be excluded from your Serverless Function. If you’re using a Community Runtime, the behavior might vary. + maxLength: 256 + type: string + includeFiles: + description: A glob pattern to match files that should be included in your Serverless Function. If you’re using a Community Runtime, the behavior might vary. + maxLength: 256 + type: string + maxDuration: + description: An integer defining how long your Serverless Function should be allowed to run on every request in seconds (between 1 and the maximum limit of your plan). + maximum: 900 + minimum: 1 + type: number + memory: + description: An integer defining the memory your Serverless Function should be provided with (between 128 and 3008). + maximum: 3008 + minimum: 128 + type: number + runtime: + description: The npm package name of a Runtime, including its version + maxLength: 256 + type: string + type: object + description: An object describing custom options for your Serverless Functions. Each key must be glob pattern that matches the paths of the Serverless Functions you would like to customize (like `api/*.js` or `api/test.js`). + examples: + - src/pages/**: + maxDuration: 6 + memory: 1024 + maxProperties: 50 + minProperties: 1 + type: object + git: + properties: + deploymentEnabled: + description: Specifies the branches that will not trigger an auto-deployment when committing to them. Any non specified branch is `true` by default. + examples: + - main: false + oneOf: + - type: boolean + - additionalProperties: + type: boolean + type: object + type: object + gitMetadata: + additionalProperties: false + description: Populates initial git metadata for different git providers. + properties: + commitAuthorName: + description: The name of the author of the commit + examples: + - kyliau + type: string + commitMessage: + description: The commit message + examples: + - add method to measure Interaction to Next Paint (INP) (#36490) + type: string + commitRef: + description: The branch on which the commit was made + examples: + - main + type: string + commitSha: + description: The hash of the commit + examples: + - dc36199b2234c6586ebe05ec94078a895c707e29 + type: string + dirty: + description: Whether or not there have been modifications to the working tree since the latest commit + examples: + - true + type: boolean + remoteUrl: + description: The git repository's remote origin url + examples: + - https://github.com/vercel/next.js + type: string + type: object + gitSource: + anyOf: + - properties: + ref: + type: string + repoId: + oneOf: + - type: number + - type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - repoId + type: object + - properties: + org: + type: string + ref: + type: string + repo: + type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - org + - repo + type: object + - properties: + projectId: + oneOf: + - type: number + - type: string + ref: + type: string + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - ref + - projectId + type: object + - properties: + ref: + type: string + repoUuid: + type: string + sha: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - ref + - repoUuid + type: object + - properties: + owner: + type: string + ref: + type: string + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + required: + - type + - ref + - owner + - slug + type: object + description: Defines the Git Repository source to be deployed. This property can not be used in combination with `files`. + headers: + description: A list of header definitions. + items: + additionalProperties: false + properties: + has: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + headers: + description: An array of key/value pairs representing each response header. + items: + additionalProperties: false + properties: + key: + maxLength: 4096 + type: string + value: + maxLength: 4096 + type: string + required: + - key + - value + type: object + maxItems: 1024 + type: array + missing: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + source: + description: A pattern that matches each incoming pathname (excluding querystring) + maxLength: 4096 + type: string + required: + - source + - headers + type: object + maxItems: 1024 + type: array + ignoreCommand: + maxLength: 256 + type: + - string + - "null" + images: + additionalProperties: false + properties: + contentDispositionType: + enum: + - inline + - attachment + contentSecurityPolicy: + maxLength: 256 + type: string + dangerouslyAllowSVG: + type: boolean + domains: + items: + maxLength: 256 + type: string + maxItems: 50 + minItems: 0 + type: array + formats: + items: + enum: + - image/avif + - image/webp + - image/jpeg + - image/png + maxItems: 4 + minItems: 1 + type: array + minimumCacheTTL: + maximum: 315360000 + minimum: 1 + type: integer + remotePatterns: + items: + additionalProperties: false + properties: + hostname: + maxLength: 256 + type: string + pathname: + maxLength: 256 + type: string + port: + maxLength: 5 + type: string + protocol: + enum: + - http + - https + required: + - hostname + type: object + maxItems: 50 + minItems: 0 + type: array + sizes: + items: + type: number + maxItems: 50 + minItems: 1 + type: array + required: + - sizes + type: object + installCommand: + description: The install command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + meta: + additionalProperties: + maxLength: 65536 + type: string + description: An object containing the deployment's metadata. Multiple key-value pairs can be attached to a deployment + examples: + - foo: bar + maxProperties: 100 + type: object + monorepoManager: + description: The monorepo manager that is being used for this deployment. When `null` is used no monorepo manager is selected + type: + - string + - "null" + name: + description: A string with the project name used in the deployment URL + examples: + - my-instant-deployment + type: string + outputDirectory: + description: The output directory of the project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + project: + description: The target project identifier in which the deployment will be created. When defined, this parameter overrides name + examples: + - my-deployment-project + type: string + projectSettings: + additionalProperties: false + description: Project settings that will be applied to the deployment. It is required for the first deployment of a project and will be saved for any following deployments + properties: + buildCommand: + description: The build command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + commandForIgnoringBuildStep: + maxLength: 256 + type: + - string + - "null" + devCommand: + description: The dev command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + framework: + description: The framework that is being used for this project. When `null` is used no framework is selected + enum: + - null + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + installCommand: + description: The install command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + outputDirectory: + description: The output directory of the project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + rootDirectory: + description: The name of a directory or relative path to the source code of your project. When `null` is used it will default to the project root + maxLength: 256 + type: + - string + - "null" + serverlessFunctionRegion: + description: The region to deploy Serverless Functions in this project + maxLength: 4 + type: + - string + - "null" + skipGitConnectDuringLink: + deprecated: true + description: Opts-out of the message prompting a CLI user to connect a Git repository in `vercel link`. + type: boolean + sourceFilesOutsideRootDirectory: + description: Indicates if there are source files outside of the root directory, typically used for monorepos + type: boolean + type: object + public: + description: Whether a deployment's source and logs are available publicly + type: boolean + redirects: + description: A list of redirect definitions. + items: + additionalProperties: false + properties: + destination: + description: A location destination defined as an absolute pathname or external URL. + maxLength: 4096 + type: string + has: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + missing: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + permanent: + description: A boolean to toggle between permanent and temporary redirect. When `true`, the status code is `308`. When `false` the status code is `307`. + type: boolean + source: + description: A pattern that matches each incoming pathname (excluding querystring). + maxLength: 4096 + type: string + required: + - source + - destination + type: object + maxItems: 1024 + title: Redirects + type: array + regions: + description: An array of the regions the deployment's Serverless Functions should be deployed to + examples: + - - sfo + - bru + items: + maxLength: 256 + type: string + maxItems: 1000 + minItems: 1 + type: array + rewrites: + description: A list of rewrite definitions. + items: + additionalProperties: false + properties: + destination: + description: An absolute pathname to an existing resource or an external URL. + maxLength: 4096 + type: string + has: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + missing: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + source: + description: A pattern that matches each incoming pathname (excluding querystring). + maxLength: 4096 + type: string + required: + - source + - destination + type: object + maxItems: 1024 + type: array + routes: + deprecated: true + description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + items: + anyOf: + - additionalProperties: false + properties: + caseSensitive: + type: boolean + check: + type: boolean + continue: + type: boolean + dest: + maxLength: 4096 + type: string + has: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + headers: + additionalProperties: + maxLength: 4096 + type: string + maxProperties: 100 + minProperties: 1 + type: object + important: + type: boolean + isInternal: + type: boolean + locale: + additionalProperties: false + minProperties: 1 + properties: + cookie: + maxLength: 4096 + type: string + default: + maxLength: 4096 + type: string + path: + maxLength: 4096 + type: string + redirect: + additionalProperties: + maxLength: 4096 + type: string + maxProperties: 100 + minProperties: 1 + type: object + value: + maxLength: 4096 + type: string + type: object + methods: + items: + maxLength: 32 + type: string + maxItems: 10 + type: array + middleware: + type: number + middlewarePath: + type: string + middlewareRawSrc: + items: + type: string + type: array + missing: + description: An array of requirements that are needed to match + items: + anyOf: + - additionalProperties: false + properties: + type: + description: The type of request element to check + enum: + - host + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - value + type: object + - additionalProperties: false + properties: + key: + description: The name of the element contained in the particular type + maxLength: 4096 + type: string + type: + description: The type of request element to check + enum: + - header + - cookie + - query + type: string + value: + description: A regular expression used to match the value. Named groups can be used in the destination + maxLength: 4096 + type: string + required: + - type + - key + type: object + maxItems: 16 + type: array + override: + type: boolean + src: + maxLength: 4096 + type: string + status: + maximum: 999 + minimum: 100 + type: integer + user: + type: boolean + required: + - src + type: object + - additionalProperties: false + properties: + handle: + enum: + - error + - filesystem + - hit + - miss + - resource + - rewrite + maxLength: 32 + type: string + required: + - handle + type: object + maxItems: 1024 + type: array + target: + description: Either not defined, `staging`, or `production`. If `staging`, a staging alias in the format `-.vercel.app` will be assigned. If `production`, any aliases defined in `alias` will be assigned. If omitted, the target will be `preview` + enum: + - staging + - production + type: string + trailingSlash: + description: When `false`, visiting a path that ends with a forward slash will respond with a `308` status code and redirect to the path without the trailing slash. + type: boolean + withLatestCommit: + description: When `true` and `deploymentId` is passed in, the sha from the previous deployment's `gitSource` is removed forcing the latest commit to be used. + type: boolean + required: + - name + type: object + responses: + "200": + content: + application/json: + schema: + description: The successfully created deployment + properties: + alias: + description: A list of all the aliases (default aliases, staging aliases and production aliases) that were assigned upon deployment creation + examples: + - [] + items: + type: string + type: array + aliasAssigned: + description: A boolean that will be true when the aliases from the alias property were assigned successfully + examples: + - true + type: boolean + aliasAssignedAt: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + description: An object that will contain a `code` and a `message` when the aliasing fails, otherwise the value will be `null` + examples: + - null + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + aliasWarning: + properties: + action: + type: string + code: + type: string + link: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + automaticAliases: + items: + type: string + type: array + bootedAt: + type: number + build: + properties: + env: + description: The keys of the environment variables that were assigned during the build phase. + examples: + - - MY_ENV_VAR + items: + type: string + type: array + required: + - env + type: object + buildErrorAt: + type: number + buildingAt: + type: number + builds: + items: + type: object + type: array + canceledAt: + type: number + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + description: The ID of Vercel Connect configuration used for this deployment + type: string + createdAt: + description: A number containing the date when the deployment was created in milliseconds + examples: + - 1540257589405 + type: number + createdIn: + description: The region where the deployment was first created + examples: + - sfo1 + type: string + creator: + description: Information about the deployment creator + properties: + uid: + description: The ID of the user that created the deployment + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: The username of the user that created the deployment + examples: + - john-doe + type: string + required: + - uid + type: object + env: + description: The keys of the environment variables that were assigned during runtime + examples: + - - MY_SECRET + items: + type: string + type: array + errorCode: + type: string + errorLink: + type: string + errorMessage: + type: + - string + - "null" + errorStep: + type: string + functions: + additionalProperties: + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + properties: + excludeFiles: + type: string + includeFiles: + type: string + maxDuration: + type: number + memory: + type: number + runtime: + type: string + type: object + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + type: + - object + - "null" + gitRepo: + oneOf: + - properties: + defaultBranch: + type: string + name: + type: string + namespace: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + projectId: + type: number + type: + enum: + - gitlab + type: string + url: + type: string + required: + - namespace + - projectId + - type + - url + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + org: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + repo: + type: string + repoId: + type: number + repoOwnerId: + type: string + type: + enum: + - github + type: string + required: + - org + - repo + - repoId + - type + - repoOwnerId + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + owner: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + repoUuid: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - owner + - repoUuid + - slug + - type + - workspaceUuid + - path + - defaultBranch + - name + - private + - ownerType + type: object + type: "null" + gitSource: + oneOf: + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoId: + oneOf: + - type: string + - type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - repoId + type: object + - properties: + org: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repo: + type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - org + - repo + type: object + - properties: + prId: + type: + - number + - "null" + projectId: + oneOf: + - type: string + - type: number + ref: + type: + - string + - "null" + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - projectId + type: object + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoUuid: + type: string + sha: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - repoUuid + type: object + - properties: + owner: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + required: + - type + - owner + - slug + type: object + - properties: + gitUrl: + type: string + ref: + type: string + sha: + type: string + type: + enum: + - custom + type: string + required: + - type + - ref + - sha + - gitUrl + type: object + - properties: + org: + type: string + ref: + type: string + repo: + type: string + repoId: + type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - sha + - repoId + type: object + - properties: + projectId: + type: number + ref: + type: string + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - ref + - sha + - projectId + type: object + - properties: + owner: + type: string + ref: + type: string + repoUuid: + type: string + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - ref + - sha + - workspaceUuid + - repoUuid + type: object + id: + description: A string holding the unique ID of the deployment + examples: + - dpl_89qyp1cskzkLrVicDaZoDbjyHuDJ + type: string + inspectorUrl: + description: Vercel URL to inspect the deployment. + examples: + - https://vercel.com/acme/nextjs/J1hXN00qjUeoYfpEEf7dnDtpSiVq + type: + - string + - "null" + isInConcurrentBuildsQueue: + description: Is the deployment currently queued waiting for a Concurrent Build Slot to be available + examples: + - false + type: boolean + lambdas: + items: + properties: + createdAt: + type: number + entrypoint: + type: + - string + - "null" + id: + type: string + output: + items: + properties: + functionName: + type: string + path: + type: string + required: + - path + - functionName + type: object + type: array + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - READY + type: string + readyStateAt: + type: number + required: + - id + - output + type: object + type: array + meta: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + monorepoManager: + description: An monorepo manager that was used for the deployment + examples: + - turbo + type: + - string + - "null" + name: + description: The name of the project associated with the deployment at the time that the deployment was created + examples: + - my-project + type: string + ownerId: + description: The unique ID of the user or team the deployment belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + plan: + description: The pricing plan the deployment was made under + enum: + - hobby + - enterprise + - pro + - oss + examples: + - pro + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + projectId: + description: The ID of the project the deployment is associated with + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + public: + description: A boolean representing if the deployment is public or not. By default this is `false` + examples: + - false + type: boolean + readyState: + description: The state of the deployment depending on the process of deploying, or if it is ready or in an error state + enum: + - QUEUED + - BUILDING + - ERROR + - INITIALIZING + - READY + - CANCELED + examples: + - READY + type: string + regions: + description: The regions the deployment exists in + examples: + - - sfo1 + items: + type: string + type: array + routes: + description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + items: + oneOf: + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + caseSensitive: + type: boolean + check: + type: boolean + continue: + type: boolean + dest: + type: string + has: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + headers: + additionalProperties: + type: string + type: object + important: + type: boolean + locale: + properties: + cookie: + type: string + redirect: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + type: object + methods: + items: + type: string + type: array + middleware: + description: A middleware index in the `middleware` key under the build result + type: number + middlewarePath: + description: A middleware key within the `output` key under the build result. Overrides a `middleware` definition. + type: string + middlewareRawSrc: + description: The original middleware matchers. + items: + type: string + type: array + missing: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + override: + type: boolean + src: + type: string + status: + type: number + required: + - src + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + dest: + type: string + handle: + enum: + - filesystem + - hit + - miss + - rewrite + - error + - resource + type: string + src: + type: string + status: + type: number + required: + - handle + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + continue: + type: boolean + middleware: + enum: + - 0 + type: number + src: + type: string + required: + - src + - continue + - middleware + type: object + type: + - array + - "null" + source: + description: Where was the deployment created from + enum: + - cli + - git + - import + - import/repo + - clone/repo + examples: + - cli + type: string + target: + description: If defined, either `staging` if a staging alias in the format `..now.sh` was assigned upon creation, or `production` if the aliases from `alias` were assigned + enum: + - production + - staging + examples: + - null + type: + - string + - "null" + team: + description: The team that owns the deployment if any + properties: + id: + description: The ID of the team owner + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + name: + description: The name of the team owner + examples: + - FSociety + type: string + slug: + description: The slug of the team owner + examples: + - fsociety + type: string + required: + - id + - name + - slug + type: object + type: + enum: + - LAMBDAS + type: string + url: + description: A string with the unique URL of the deployment + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + userAliases: + description: An array of domains that were provided by the user when creating the Deployment. + examples: + - - sub1.example.com + - sub2.example.com + items: + type: string + type: array + version: + description: The platform version that was used to create the deployment. + enum: + - 2 + examples: + - 2 + type: number + required: + - build + - createdIn + - env + - inspectorUrl + - isInConcurrentBuildsQueue + - meta + - name + - ownerId + - plan + - projectId + - routes + - alias + - aliasAssigned + - bootedAt + - buildingAt + - createdAt + - creator + - id + - public + - readyState + - regions + - type + - url + - version + type: object + description: The successfully created deployment + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + Deploying to Serverless Functions to multiple regions requires a plan update + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: The deployment project is being transferred + security: + - bearerToken: [] + summary: Create a new deployment + tags: + - deployments + "/v13/deployments/{idOrUrl}": + get: + description: Retrieves information for a deployment either by supplying its ID (`id` property) or Hostname (`url` property). Additional details will be included when the authenticated user is an owner of the deployment. + operationId: getDeployment + parameters: + - description: The unique identifier or hostname of the deployment. + in: path + name: idOrUrl + required: true + schema: + description: The unique identifier or hostname of the deployment. + examples: + - dpl_89qyp1cskzkLrVicDaZoDbjyHuDJ + type: string + - description: Whether to add in gitRepo information. + in: query + name: withGitRepoInfo + required: false + schema: + description: Whether to add in gitRepo information. + examples: + - "true" + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - description: The deployment including both public and private information + properties: + alias: + description: A list of all the aliases (default aliases, staging aliases and production aliases) that were assigned upon deployment creation + examples: + - [] + items: + type: string + type: array + aliasAssigned: + description: A boolean that will be true when the aliases from the alias property were assigned successfully + examples: + - true + type: boolean + aliasAssignedAt: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + description: An object that will contain a `code` and a `message` when the aliasing fails, otherwise the value will be `null` + examples: + - null + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + aliasWarning: + properties: + action: + type: string + code: + type: string + link: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + automaticAliases: + items: + type: string + type: array + bootedAt: + type: number + build: + properties: + env: + description: The keys of the environment variables that were assigned during the build phase. + examples: + - - MY_ENV_VAR + items: + type: string + type: array + required: + - env + type: object + buildErrorAt: + type: number + buildingAt: + type: number + builds: + items: + type: object + type: array + canceledAt: + type: number + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + description: The ID of Vercel Connect configuration used for this deployment + type: string + createdAt: + description: A number containing the date when the deployment was created in milliseconds + examples: + - 1540257589405 + type: number + createdIn: + description: The region where the deployment was first created + examples: + - sfo1 + type: string + creator: + description: Information about the deployment creator + properties: + uid: + description: The ID of the user that created the deployment + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: The username of the user that created the deployment + examples: + - john-doe + type: string + required: + - uid + type: object + env: + description: The keys of the environment variables that were assigned during runtime + examples: + - - MY_SECRET + items: + type: string + type: array + errorCode: + type: string + errorLink: + type: string + errorMessage: + type: + - string + - "null" + errorStep: + type: string + functions: + additionalProperties: + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + properties: + excludeFiles: + type: string + includeFiles: + type: string + maxDuration: + type: number + memory: + type: number + runtime: + type: string + type: object + description: An object used to configure your Serverless Functions + examples: + - api/test.js: + memory: 3008 + type: + - object + - "null" + gitRepo: + oneOf: + - properties: + defaultBranch: + type: string + name: + type: string + namespace: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + projectId: + type: number + type: + enum: + - gitlab + type: string + url: + type: string + required: + - namespace + - projectId + - type + - url + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + org: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + repo: + type: string + repoId: + type: number + repoOwnerId: + type: string + type: + enum: + - github + type: string + required: + - org + - repo + - repoId + - type + - repoOwnerId + - path + - defaultBranch + - name + - private + - ownerType + type: object + - properties: + defaultBranch: + type: string + name: + type: string + owner: + type: string + ownerType: + enum: + - team + - user + type: string + path: + type: string + private: + type: boolean + repoUuid: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - owner + - repoUuid + - slug + - type + - workspaceUuid + - path + - defaultBranch + - name + - private + - ownerType + type: object + type: "null" + gitSource: + oneOf: + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoId: + oneOf: + - type: string + - type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - repoId + type: object + - properties: + org: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repo: + type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - org + - repo + type: object + - properties: + prId: + type: + - number + - "null" + projectId: + oneOf: + - type: string + - type: number + ref: + type: + - string + - "null" + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - projectId + type: object + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoUuid: + type: string + sha: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - repoUuid + type: object + - properties: + owner: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + required: + - type + - owner + - slug + type: object + - properties: + gitUrl: + type: string + ref: + type: string + sha: + type: string + type: + enum: + - custom + type: string + required: + - type + - ref + - sha + - gitUrl + type: object + - properties: + org: + type: string + ref: + type: string + repo: + type: string + repoId: + type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - sha + - repoId + type: object + - properties: + projectId: + type: number + ref: + type: string + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - ref + - sha + - projectId + type: object + - properties: + owner: + type: string + ref: + type: string + repoUuid: + type: string + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - ref + - sha + - workspaceUuid + - repoUuid + type: object + id: + description: A string holding the unique ID of the deployment + examples: + - dpl_89qyp1cskzkLrVicDaZoDbjyHuDJ + type: string + inspectorUrl: + description: Vercel URL to inspect the deployment. + examples: + - https://vercel.com/acme/nextjs/J1hXN00qjUeoYfpEEf7dnDtpSiVq + type: + - string + - "null" + isInConcurrentBuildsQueue: + description: Is the deployment currently queued waiting for a Concurrent Build Slot to be available + examples: + - false + type: boolean + lambdas: + items: + properties: + createdAt: + type: number + entrypoint: + type: + - string + - "null" + id: + type: string + output: + items: + properties: + functionName: + type: string + path: + type: string + required: + - path + - functionName + type: object + type: array + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - READY + type: string + readyStateAt: + type: number + required: + - id + - output + type: object + type: array + meta: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + monorepoManager: + description: An monorepo manager that was used for the deployment + examples: + - turbo + type: + - string + - "null" + name: + description: The name of the project associated with the deployment at the time that the deployment was created + examples: + - my-project + type: string + ownerId: + description: The unique ID of the user or team the deployment belongs to + examples: + - ZspSRT4ljIEEmMHgoDwKWDei + type: string + plan: + description: The pricing plan the deployment was made under + enum: + - hobby + - enterprise + - pro + - oss + examples: + - pro + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + projectId: + description: The ID of the project the deployment is associated with + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + public: + description: A boolean representing if the deployment is public or not. By default this is `false` + examples: + - false + type: boolean + readyState: + description: The state of the deployment depending on the process of deploying, or if it is ready or in an error state + enum: + - QUEUED + - BUILDING + - ERROR + - INITIALIZING + - READY + - CANCELED + examples: + - READY + type: string + regions: + description: The regions the deployment exists in + examples: + - - sfo1 + items: + type: string + type: array + routes: + description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + items: + oneOf: + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + caseSensitive: + type: boolean + check: + type: boolean + continue: + type: boolean + dest: + type: string + has: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + headers: + additionalProperties: + type: string + type: object + important: + type: boolean + locale: + properties: + cookie: + type: string + redirect: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + type: object + methods: + items: + type: string + type: array + middleware: + description: A middleware index in the `middleware` key under the build result + type: number + middlewarePath: + description: A middleware key within the `output` key under the build result. Overrides a `middleware` definition. + type: string + middlewareRawSrc: + description: The original middleware matchers. + items: + type: string + type: array + missing: + items: + oneOf: + - properties: + type: + enum: + - host + type: string + value: + type: string + required: + - type + - value + type: object + - properties: + key: + type: string + type: + enum: + - header + - cookie + - query + type: string + value: + type: string + required: + - type + - key + type: object + type: array + override: + type: boolean + src: + type: string + status: + type: number + required: + - src + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + dest: + type: string + handle: + enum: + - filesystem + - hit + - miss + - rewrite + - error + - resource + type: string + src: + type: string + status: + type: number + required: + - handle + type: object + - description: A list of routes objects used to rewrite paths to point towards other internal or external paths + examples: + - - dest: https://docs.example.com + src: /docs + properties: + continue: + type: boolean + middleware: + enum: + - 0 + type: number + src: + type: string + required: + - src + - continue + - middleware + type: object + type: + - array + - "null" + source: + description: Where was the deployment created from + enum: + - cli + - git + - import + - import/repo + - clone/repo + examples: + - cli + type: string + target: + description: If defined, either `staging` if a staging alias in the format `..now.sh` was assigned upon creation, or `production` if the aliases from `alias` were assigned + enum: + - production + - staging + examples: + - null + type: + - string + - "null" + team: + description: The team that owns the deployment if any + properties: + id: + description: The ID of the team owner + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + name: + description: The name of the team owner + examples: + - FSociety + type: string + slug: + description: The slug of the team owner + examples: + - fsociety + type: string + required: + - id + - name + - slug + type: object + type: + enum: + - LAMBDAS + type: string + url: + description: A string with the unique URL of the deployment + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + userAliases: + description: An array of domains that were provided by the user when creating the Deployment. + examples: + - - sub1.example.com + - sub2.example.com + items: + type: string + type: array + version: + description: The platform version that was used to create the deployment. + enum: + - 2 + examples: + - 2 + type: number + required: + - build + - createdIn + - env + - inspectorUrl + - isInConcurrentBuildsQueue + - meta + - name + - ownerId + - plan + - projectId + - routes + - alias + - aliasAssigned + - bootedAt + - buildingAt + - createdAt + - creator + - id + - public + - readyState + - regions + - type + - url + - version + type: object + - description: The deployment including only public information + properties: + alias: + description: A list of all the aliases (default aliases, staging aliases and production aliases) that were assigned upon deployment creation + examples: + - [] + items: + type: string + type: array + aliasAssigned: + description: A boolean that will be true when the aliases from the alias property were assigned successfully + examples: + - true + type: boolean + aliasError: + description: An object that will contain a `code` and a `message` when the aliasing fails, otherwise the value will be `null` + examples: + - null + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + aliasWarning: + properties: + action: + type: string + code: + type: string + link: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + automaticAliases: + items: + type: string + type: array + bootedAt: + type: number + buildErrorAt: + type: number + buildingAt: + type: number + canceledAt: + type: number + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + createdAt: + description: A number containing the date when the deployment was created in milliseconds + examples: + - 1540257589405 + type: number + creator: + description: Information about the deployment creator + properties: + uid: + description: The ID of the user that created the deployment + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: The username of the user that created the deployment + examples: + - john-doe + type: string + required: + - uid + type: object + errorCode: + type: string + errorLink: + type: string + errorMessage: + type: + - string + - "null" + errorStep: + type: string + gitSource: + oneOf: + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoId: + oneOf: + - type: string + - type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - repoId + type: object + - properties: + org: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repo: + type: string + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - org + - repo + type: object + - properties: + prId: + type: + - number + - "null" + projectId: + oneOf: + - type: string + - type: number + ref: + type: + - string + - "null" + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - projectId + type: object + - properties: + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + repoUuid: + type: string + sha: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - repoUuid + type: object + - properties: + owner: + type: string + prId: + type: + - number + - "null" + ref: + type: + - string + - "null" + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + required: + - type + - owner + - slug + type: object + - properties: + gitUrl: + type: string + ref: + type: string + sha: + type: string + type: + enum: + - custom + type: string + required: + - type + - ref + - sha + - gitUrl + type: object + - properties: + org: + type: string + ref: + type: string + repo: + type: string + repoId: + type: number + sha: + type: string + type: + enum: + - github + type: string + required: + - type + - ref + - sha + - repoId + type: object + - properties: + projectId: + type: number + ref: + type: string + sha: + type: string + type: + enum: + - gitlab + type: string + required: + - type + - ref + - sha + - projectId + type: object + - properties: + owner: + type: string + ref: + type: string + repoUuid: + type: string + sha: + type: string + slug: + type: string + type: + enum: + - bitbucket + type: string + workspaceUuid: + type: string + required: + - type + - ref + - sha + - workspaceUuid + - repoUuid + type: object + id: + description: A string holding the unique ID of the deployment + examples: + - dpl_89qyp1cskzkLrVicDaZoDbjyHuDJ + type: string + lambdas: + items: + properties: + createdAt: + type: number + entrypoint: + type: + - string + - "null" + id: + type: string + output: + items: + properties: + functionName: + type: string + path: + type: string + required: + - path + - functionName + type: object + type: array + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - READY + type: string + readyStateAt: + type: number + required: + - id + - output + type: object + type: array + meta: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + name: + description: The name of the project associated with the deployment at the time that the deployment was created + examples: + - my-project + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + public: + description: A boolean representing if the deployment is public or not. By default this is `false` + examples: + - false + type: boolean + readyState: + description: The state of the deployment depending on the process of deploying, or if it is ready or in an error state + enum: + - QUEUED + - BUILDING + - ERROR + - INITIALIZING + - READY + - CANCELED + examples: + - READY + type: string + regions: + description: The regions the deployment exists in + examples: + - - sfo1 + items: + type: string + type: array + source: + description: Where was the deployment created from + enum: + - cli + - git + - import + - import/repo + - clone/repo + examples: + - cli + type: string + target: + description: If defined, either `staging` if a staging alias in the format `..now.sh` was assigned upon creation, or `production` if the aliases from `alias` were assigned + enum: + - production + - staging + examples: + - null + type: + - string + - "null" + team: + description: The team that owns the deployment if any + properties: + id: + description: The ID of the team owner + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: string + name: + description: The name of the team owner + examples: + - FSociety + type: string + slug: + description: The slug of the team owner + examples: + - fsociety + type: string + required: + - id + - name + - slug + type: object + type: + enum: + - LAMBDAS + type: string + url: + description: A string with the unique URL of the deployment + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + userAliases: + description: An array of domains that were provided by the user when creating the Deployment. + examples: + - - sub1.example.com + - sub2.example.com + items: + type: string + type: array + version: + description: The platform version that was used to create the deployment. + enum: + - 2 + examples: + - 2 + type: number + required: + - alias + - aliasAssigned + - bootedAt + - buildingAt + - createdAt + - creator + - id + - name + - meta + - public + - readyState + - regions + - type + - url + - version + type: object + description: |- + The deployment including only public information + The deployment including both public and private information + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: Get a deployment by ID or URL + tags: + - deployments + "/v13/deployments/{id}": + delete: + description: This API allows you to delete a deployment, either by supplying its `id` in the URL or the `url` of the deployment as a query parameter. You can obtain the ID, for example, by listing all deployments. + operationId: deleteDeployment + parameters: + - description: The ID of the deployment to be deleted + in: path + name: id + required: true + schema: + description: The ID of the deployment to be deleted + examples: + - dpl_5WJWYSyB7BpgTj3EuwF37WMRBXBtPQ2iTMJHJBJyRfd + type: string + - description: A Deployment or Alias URL. In case it is passed, the ID will be ignored + in: query + name: url + required: false + schema: + description: A Deployment or Alias URL. In case it is passed, the ID will be ignored + examples: + - https://files-orcin-xi.vercel.app/ + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + state: + description: A constant with the final state of the deployment. + enum: + - DELETED + type: string + uid: + description: The removed deployment ID. + examples: + - dpl_5WJWYSyB7BpgTj3EuwF37WMRBXBtPQ2iTMJHJBJyRfd + type: string + required: + - uid + - state + type: object + description: The deployment was successfully deleted + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: Delete a Deployment + tags: + - deployments + "/v2/aliases/{aliasId}": + delete: + description: Delete an Alias with the specified ID. + operationId: deleteAlias + parameters: + - description: The ID or alias that will be removed + in: path + name: aliasId + required: true + schema: + description: The ID or alias that will be removed + examples: + - 2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + status: + enum: + - SUCCESS + type: string + required: + - status + type: object + description: The alias was successfully removed + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The alias was not found + security: + - bearerToken: [] + summary: Delete an Alias + tags: + - aliases + "/v2/deployments/{idOrUrl}/events": + get: + description: Get the build logs of a deployment by deployment ID and build ID. It can work as an infinite stream of logs or as a JSON endpoint depending on the input parameters. + operationId: getDeploymentEvents + parameters: + - description: The unique identifier or hostname of the deployment. + in: path + name: idOrUrl + required: true + schema: + description: The unique identifier or hostname of the deployment. + examples: + - dpl_5WJWYSyB7BpgTj3EuwF37WMRBXBtPQ2iTMJHJBJyRfd + type: string + - description: Order of the returned events based on the timestamp. + in: query + name: direction + required: false + schema: + default: forward + description: Order of the returned events based on the timestamp. + enum: + - backward + - forward + examples: + - backward + type: string + - description: When enabled, this endpoint will return live events as they happen. + in: query + name: follow + required: false + schema: + description: When enabled, this endpoint will return live events as they happen. + enum: + - 0 + - 1 + examples: + - 1 + type: number + - description: Maximum number of events to return. Provide `-1` to return all available logs. + in: query + name: limit + required: false + schema: + description: Maximum number of events to return. Provide `-1` to return all available logs. + examples: + - 100 + type: number + - description: Deployment build ID. + in: query + name: name + required: false + schema: + description: Deployment build ID. + examples: + - bld_cotnkcr76 + type: string + - description: Timestamp for when build logs should be pulled from. + in: query + name: since + required: false + schema: + description: Timestamp for when build logs should be pulled from. + examples: + - 1540095775941 + type: number + - description: Timestamp for when the build logs should be pulled up until. + in: query + name: until + required: false + schema: + description: Timestamp for when the build logs should be pulled up until. + examples: + - 1540106318643 + type: number + - description: HTTP status code range to filter events by. + in: query + name: statusCode + required: false + schema: + description: HTTP status code range to filter events by. + examples: + - 5xx + oneOf: + - type: number + - type: string + - in: query + name: delimiter + required: false + schema: + enum: + - 0 + - 1 + examples: + - 1 + type: number + - in: query + name: builds + required: false + schema: + enum: + - 0 + - 1 + examples: + - 1 + type: number + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + oneOf: + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - id + - date + - serial + type: object + type: + enum: + - command + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - deployment-state + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - delimiter + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + created: + type: number + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - date + - id + - deploymentId + - created + - serial + type: object + type: + enum: + - exit + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - middleware + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + statusCode: + type: number + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - command + - stdout + - stderr + - exit + - deployment-state + - delimiter + - middleware + - middleware-invocation + - edge-function-invocation + - fatal + type: string + required: + - type + - created + - payload + type: object + type: array + application/stream+json: + schema: + oneOf: + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - id + - date + - serial + type: object + type: + enum: + - command + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - deployment-state + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - delimiter + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + created: + type: number + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - date + - id + - deploymentId + - created + - serial + type: object + type: + enum: + - exit + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - middleware + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + statusCode: + type: number + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - command + - stdout + - stderr + - exit + - deployment-state + - delimiter + - middleware + - middleware-invocation + - edge-function-invocation + - fatal + type: string + required: + - type + - created + - payload + type: object + - oneOf: + - type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - id + - date + - serial + type: object + type: + enum: + - command + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - deployment-state + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + serial: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - delimiter + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + created: + type: number + date: + type: number + deploymentId: + type: string + id: + type: string + serial: + type: string + text: + type: string + required: + - date + - id + - deploymentId + - created + - serial + type: object + type: + enum: + - exit + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - middleware + type: string + required: + - type + - created + - payload + type: object + - properties: + created: + type: number + payload: + properties: + date: + type: number + deploymentId: + type: string + id: + type: string + info: + properties: + entrypoint: + type: string + name: + type: string + path: + type: string + step: + type: string + type: + type: string + required: + - type + - name + type: object + requestId: + type: string + serial: + type: string + statusCode: + type: number + text: + type: string + required: + - deploymentId + - info + - id + - date + - serial + type: object + type: + enum: + - command + - stdout + - stderr + - exit + - deployment-state + - delimiter + - middleware + - middleware-invocation + - edge-function-invocation + - fatal + type: string + required: + - type + - created + - payload + type: object + description: |- + A stream of jsonlines where each line is a deployment log item. + Array of deployment logs for the provided query. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: Get deployment events + tags: + - deployments + "/v2/deployments/{id}/aliases": + get: + description: Retrieves all Aliases for the Deployment with the given ID. The authenticated User must own the deployment. + operationId: listDeploymentAliases + parameters: + - description: The ID of the deployment the aliases should be listed for + in: path + name: id + required: true + schema: + description: The ID of the deployment the aliases should be listed for + examples: + - dpl_FjvFJncQHQcZMznrUm9EoB8sFuPa + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + aliases: + description: A list of the aliases assigned to the deployment + items: + description: A list of the aliases assigned to the deployment + properties: + alias: + description: The alias name, it could be a `.vercel.app` subdomain or a custom domain + examples: + - my-alias.vercel.app + type: string + created: + description: The date when the alias was created + examples: + - 2017-04-26T23:00:34.232Z + format: date-time + type: string + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + redirect: + description: Target destination domain for redirect when the alias is a redirect + type: + - string + - "null" + uid: + description: The unique identifier of the alias + examples: + - 2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + required: + - uid + - alias + - created + type: object + type: array + required: + - aliases + type: object + description: The list of aliases assigned to the deployment + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The deployment was not found + security: + - bearerToken: [] + summary: List Deployment Aliases + tags: + - aliases + post: + description: Creates a new alias for the deployment with the given deployment ID. The authenticated user must own this deployment. If the desired alias is already assigned to another deployment, then it will be removed from the old deployment and assigned to the new one. + operationId: assignAlias + parameters: + - description: The ID of the deployment the aliases should be listed for + in: path + name: id + required: true + schema: + description: The ID of the deployment the aliases should be listed for + examples: + - dpl_FjvFJncQHQcZMznrUm9EoB8sFuPa + oneOf: + - type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + alias: + description: The alias we want to assign to the deployment defined in the URL + examples: + - my-alias.vercel.app + type: string + redirect: + description: The redirect property will take precedence over the deployment id from the URL and consists of a hostname (like test.com) to which the alias should redirect using status code 307 + examples: + - null + type: + - string + - "null" + type: object + responses: + "200": + content: + application/json: + schema: + properties: + alias: + description: The assigned alias name + examples: + - my-alias.vercel.app + type: string + created: + description: The date when the alias was created + examples: + - 2017-04-26T23:00:34.232Z + format: date-time + type: string + oldDeploymentId: + description: The unique identifier of the previously aliased deployment, only received when the alias was used before + examples: + - dpl_FjvFJncQHQcZMznrUm9EoB8sFuPa + type: + - string + - "null" + uid: + description: The unique identifier of the alias + examples: + - 2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + required: + - uid + - alias + - created + type: object + description: The alias was successfully assigned to the deployment + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The cert for the provided alias is not ready + The deployment is not READY and can not be aliased + The supplied alias is invalid + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + You do not have permission to access this resource. + If no .vercel.app alias exists then we fail (nothing to mirror) + "404": + description: |- + The domain used for the alias was not found + The project for the given project can not be found + The deployment was not found + "409": + description: The provided alias is already assigned to the given deployment + security: + - bearerToken: [] + summary: Assign an Alias + tags: + - aliases + "/v2/domains/{domain}/records": + post: + description: Creates a DNS record for a domain. + operationId: createRecord + parameters: + - description: The domain used to create the DNS record. + in: path + name: domain + required: true + schema: + description: The domain used to create the DNS record. + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + anyOf: + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `A`. + enum: + - A + type: string + value: + description: The record value must be a valid IPv4 address. + examples: + - 192.0.2.42 + format: ipv4 + type: string + required: + - type + - value + - name + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `AAAA`. + enum: + - AAAA + type: string + value: + description: An AAAA record pointing to an IPv6 address. + examples: + - 2001:DB8::42 + format: ipv6 + type: string + required: + - type + - value + - name + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `ALIAS`. + enum: + - ALIAS + type: string + value: + description: An ALIAS virtual record pointing to a hostname resolved to an A record on server side. + examples: + - cname.vercel-dns.com + type: string + required: + - type + - value + - name + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `CAA`. + enum: + - CAA + type: string + value: + description: A CAA record to specify which Certificate Authorities (CAs) are allowed to issue certificates for the domain. + examples: + - 0 issue \"letsencrypt.org\" + type: string + required: + - type + - value + - name + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `CNAME`. + enum: + - CNAME + type: string + value: + description: A CNAME record mapping to another domain name. + examples: + - cname.vercel-dns.com + type: string + required: + - type + - name + type: object + - additionalProperties: false + properties: + mxPriority: + examples: + - 10 + maximum: 65535 + minimum: 0 + type: number + name: + description: A subdomain name or an empty string for the root domain. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `MX`. + enum: + - MX + type: string + value: + description: An MX record specifying the mail server responsible for accepting messages on behalf of the domain name. + examples: + - 10 mail.example.com. + type: string + required: + - type + - value + - name + - mxPriority + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + name: subdomain + type: string + srv: + additionalProperties: false + properties: + port: + anyOf: + - examples: + - 5000 + maximum: 65535 + minimum: 0 + type: number + - type: "null" + priority: + anyOf: + - examples: + - 10 + maximum: 65535 + minimum: 0 + type: number + - type: "null" + target: + examples: + - host.example.com + type: string + weight: + anyOf: + - examples: + - 10 + maximum: 65535 + minimum: 0 + type: number + - type: "null" + required: + - weight + - port + - priority + type: object + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `SRV`. + enum: + - SRV + type: string + required: + - type + - name + - srv + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name or an empty string for the root domain. + name: subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `TXT`. + enum: + - TXT + type: string + value: + description: A TXT record containing arbitrary text. + examples: + - hello + type: string + required: + - type + - value + - name + type: object + - additionalProperties: false + properties: + name: + description: A subdomain name. + examples: + - subdomain + type: string + ttl: + description: The TTL value. Must be a number between 60 and 2147483647. Default value is 60. + examples: + - 60 + maximum: 2147483647 + minimum: 60 + type: number + type: + description: Must be of type `NS`. + enum: + - NS + type: string + value: + description: An NS domain value. + examples: + - ns1.example.com + type: string + required: + - type + - name + type: object + properties: + type: + description: The type of record, it could be one of the valid DNS records. + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + required: + - type + responses: + "200": + content: + application/json: + schema: + oneOf: + - properties: + uid: + type: string + updated: + type: number + required: + - uid + - updated + type: object + - properties: + uid: + description: The id of the newly created DNS record + examples: + - rec_V0fra8eEgQwEpFhYG2vTzC3K + type: string + required: + - uid + type: object + description: Successful response showing the uid of the newly created DNS record. + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "401": + description: "" + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Create a DNS record + tags: + - dns + "/v2/domains/{domain}/records/{recordId}": + delete: + description: Removes an existing DNS record from a domain name. + operationId: removeRecord + parameters: + - in: path + name: domain + required: true + schema: + examples: + - example.com + type: string + - in: path + name: recordId + required: true + schema: + examples: + - rec_V0fra8eEgQwEpFhYG2vTzC3K + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + type: object + description: Successful response by removing the specified DNS record. + "400": + description: One of the provided values in the request query is invalid. + "401": + description: "" + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Delete a DNS record + tags: + - dns + /v2/files: + post: + description: Before you create a deployment you need to upload the required files for that deployment. To do it, you need to first upload each file to this endpoint. Once that's completed, you can create a new deployment with the uploaded files. The file content must be placed inside the body of the request. In the case of a successful response you'll receive a status code 200 with an empty body. + operationId: uploadFile + parameters: + - description: The file size in bytes + in: header + name: Content-Length + schema: + description: The file size in bytes + type: number + - description: The file SHA1 used to check the integrity + in: header + name: x-vercel-digest + schema: + description: The file SHA1 used to check the integrity + maxLength: 40 + type: string + - description: The file SHA1 used to check the integrity + in: header + name: x-now-digest + schema: + deprecated: true + description: The file SHA1 used to check the integrity + maxLength: 40 + type: string + - description: The file size as an alternative to `Content-Length` + in: header + name: x-now-size + schema: + deprecated: true + description: The file size as an alternative to `Content-Length` + type: number + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - properties: + urls: + description: Array of URLs where the file was updated + examples: + - - example-upload.aws.com + items: + type: string + type: array + required: + - urls + type: object + - type: object + description: |- + File already uploaded + File successfully uploaded + "400": + description: |- + One of the provided values in the headers is invalid + Digest is not valid + File size is not valid + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Upload Deployment Files + tags: + - deployments + /v2/integrations/log-drains: + get: + description: Retrieves a list of all Integration log drains that are defined for the authorized account. When using an OAuth2 token, the list is limited to log drains created by the authenticated integration. + operationId: getIntegrationLogDrains + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + properties: + branch: + description: The branch regexp of log drain + examples: + - feature/* + type: string + clientId: + description: The oauth2 client application id that created this log drain + examples: + - oac_xRhY4LAB7yLhUADD69EvV7ct + type: string + configurationId: + description: The client configuration this log drain was created with + examples: + - icfg_cuwj0AdCdH3BwWT4LPijCC7t + type: string + createdAt: + description: A timestamp that tells you when the log drain was created + examples: + - 1558531915505 + type: number + createdFrom: + description: Whether the log drain was created by an integration or by a user + enum: + - self-served + - integration + examples: + - integration + type: string + deliveryFormat: + description: The delivery log format + enum: + - json + - ndjson + - syslog + examples: + - json + type: string + environment: + description: The environment of log drain + enum: + - production + - preview + examples: + - production + type: string + headers: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + examples: + - '{"Authorization": "Bearer 123"}' + type: object + id: + description: The unique identifier of the log drain. Always prefixed with `ld_` + examples: + - ld_nBuA7zCID8g4QZ8g + type: string + name: + description: The name of the log drain + examples: + - My first log drain + type: string + ownerId: + description: The identifier of the team or user whose events will trigger the log drain + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projectId: + examples: + - AbCgVkqoxXeXCDWehVir51LHGrrcWL4mkYm14W6UBPWQeb + type: + - string + - "null" + projectIds: + description: The identifier of the projects this log drain is associated with + examples: + - AbCgVkqoxXeXCDWehVir51LHGrrcWL4mkYm14W6UBPWQeb + items: + type: string + type: array + sources: + description: The sources from which logs are currently being delivered to this log drain. + examples: + - - build + - edge + items: + description: The sources from which logs are currently being delivered to this log drain. + enum: + - static + - lambda + - build + - edge + - external + - deployment + examples: + - - build + - edge + type: string + type: array + url: + description: The URL to call when logs are generated + examples: + - https://example.com/log-drain + type: string + required: + - createdAt + - id + - name + - ownerId + - url + type: object + type: array + description: A list of log drains + "400": + description: "" + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Retrieves a list of Integration log drains + tags: + - logDrains + post: + description: Creates an Integration log drain. This endpoint must be called with an OAuth2 client (integration), since log drains are tied to integrations. If it is called with a different token type it will produce a 400 error. + operationId: createLogDrain + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + branch: + description: The branch regexp of log drain + examples: + - feature/* + type: string + deliveryFormat: + description: The delivery log format + enum: + - json + - ndjson + - syslog + examples: + - json + environment: + description: The environment of log drain + enum: + - preview + - production + examples: + - production + headers: + additionalProperties: + type: string + description: Headers to be sent together with the request + type: object + name: + description: The name of the log drain + examples: + - My first log drain + maxLength: 100 + pattern: ^[A-z0-9_ -]+$ + type: string + projectIds: + items: + pattern: ^[a-zA-z0-9_]+$ + type: string + maxItems: 50 + minItems: 1 + type: array + secret: + description: A secret to sign log drain notification headers so a consumer can verify their authenticity + examples: + - a1Xsfd325fXcs + maxLength: 100 + pattern: ^[A-z0-9_ -]+$ + type: string + sources: + items: + enum: + - static + - lambda + - build + - edge + - external + type: string + minItems: 1 + type: array + uniqueItems: true + url: + description: The url where you will receive logs. The protocol must be `https://` or `http://` when type is `json` and `ndjson`, and `syslog+tls:` or `syslog:` when the type is `syslog`. + examples: + - https://example.com/log-drain + format: uri + pattern: ^(https?|syslog\\+tls|syslog):// + type: string + required: + - name + - url + type: object + responses: + "200": + content: + application/json: + schema: + properties: + branch: + description: The branch regexp of log drain + examples: + - feature/* + type: string + clientId: + description: The oauth2 client application id that created this log drain + examples: + - oac_xRhY4LAB7yLhUADD69EvV7ct + type: string + configurationId: + description: The client configuration this log drain was created with + examples: + - icfg_cuwj0AdCdH3BwWT4LPijCC7t + type: string + createdAt: + description: A timestamp that tells you when the log drain was created + examples: + - 1558531915505 + type: number + createdFrom: + description: Whether the log drain was created by an integration or by a user + enum: + - self-served + - integration + examples: + - integration + type: string + deliveryFormat: + description: The delivery log format + enum: + - json + - ndjson + - syslog + examples: + - json + type: string + environment: + description: The environment of log drain + enum: + - preview + - production + examples: + - production + type: string + headers: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + examples: + - '{"Authorization": "Bearer 123"}' + type: object + id: + description: The unique identifier of the log drain. Always prefixed with `ld_` + examples: + - ld_nBuA7zCID8g4QZ8g + type: string + name: + description: The name of the log drain + examples: + - My first log drain + type: string + ownerId: + description: The identifier of the team or user whose events will trigger the log drain + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf + type: string + projectId: + examples: + - AbCgVkqoxXeXCDWehVir51LHGrrcWL4mkYm14W6UBPWQeb + type: + - string + - "null" + projectIds: + description: The identifier of the projects this log drain is associated with + examples: + - AbCgVkqoxXeXCDWehVir51LHGrrcWL4mkYm14W6UBPWQeb + items: + type: string + type: array + sources: + description: The sources from which logs are currently being delivered to this log drain. + examples: + - - build + - edge + items: + description: The sources from which logs are currently being delivered to this log drain. + enum: + - static + - lambda + - build + - edge + - external + - deployment + examples: + - - build + - edge + type: string + type: array + url: + description: The URL to call when logs are generated + examples: + - https://example.com/log-drain + type: string + required: + - createdAt + - id + - name + - ownerId + - url + type: object + description: The log drain was successfully created + "400": + description: |- + One of the provided values in the request body is invalid. + The provided token is not from an OAuth2 Client + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Creates a new Integration Log Drain + tags: + - logDrains + "/v2/secrets/{idOrName}": + delete: + description: This deletes the user's secret defined in the URL. + operationId: deleteSecret + parameters: + - description: The name or the unique identifier to which the secret belongs to. + in: path + name: idOrName + required: true + schema: + description: The name or the unique identifier to which the secret belongs to. + examples: + - sec_RKc5iV0rV3ZSrFrHiruRno7k + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + created: + description: The date when the secret was created. + examples: + - 2021-02-10T13:11:49.180Z + type: number + name: + description: The name of the deleted secret. + examples: + - my-api-key + type: string + uid: + description: The unique identifier of the deleted secret. + examples: + - sec_XCG7t7AIHuO2SBA8667zNUiM + type: string + required: + - uid + - name + - created + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Delete a secret + tags: + - secrets + "/v2/secrets/{name}": + patch: + description: Enables to edit the name of a user's secret. The name has to be unique to that user's secrets. + operationId: renameSecret + parameters: + - description: The name of the secret. + in: path + name: name + required: true + schema: + description: The name of the secret. + examples: + - my-api-key + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + name: + description: The name of the new secret. + examples: + - my-api-key + maximum: 100 + type: string + required: + - name + type: object + responses: + "200": + content: + application/json: + schema: + properties: + created: + description: Enables basic storage and retrieval of dates and times. + format: date-time + type: string + name: + type: string + oldName: + type: string + uid: + type: string + required: + - uid + - name + - created + - oldName + type: object + description: "" + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Change secret name + tags: + - secrets + post: + description: Allows to create a new secret. + operationId: createSecret + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + - description: Automatically added + in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + decryptable: + description: Whether the secret value can be decrypted after it has been created. + examples: + - true + type: boolean + name: + description: The name of the secret (max 100 characters). + examples: + - my-api-key + maximum: 100 + type: string + projectId: + deprecated: true + description: Associate a secret to a project. + examples: + - prj_2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + value: + description: The value of the new secret. + examples: + - some secret value + type: string + required: + - name + - value + type: object + responses: + "200": + content: + application/json: + schema: + properties: + created: + description: The date when the secret was created. + examples: + - 2021-02-10T13:11:49.180Z + format: date-time + type: string + createdAt: + description: Timestamp for when the secret was created. + examples: + - 1609492210000 + type: number + decryptable: + description: Indicates whether the secret value can be decrypted after it has been created. + examples: + - true + type: boolean + name: + description: The name of the secret. + examples: + - my-api-key + type: string + projectId: + description: The unique identifier of the project which the secret belongs to. + examples: + - prj_2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + teamId: + description: The unique identifier of the team the secret was created for. + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: + - string + - "null" + uid: + description: The unique identifier of the secret. + examples: + - sec_XCG7t7AIHuO2SBA8667zNUiM + type: string + userId: + description: The unique identifier of the user who created the secret. + examples: + - 2qDDuGFTWXBLDNnqZfWPDp1A + type: string + value: + properties: + data: + items: + type: number + type: array + type: + enum: + - Buffer + type: string + type: object + required: + - value + - created + - name + - uid + type: object + description: Successful response showing the created secret. + "400": + description: One of the provided values in the request body is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Create a new secret + tags: + - secrets + /v2/teams: + get: + description: Get a paginated list of all the Teams the authenticated User is a member of. + operationId: getTeams + parameters: + - description: Maximum number of Teams which may be returned. + in: query + name: limit + schema: + description: Maximum number of Teams which may be returned. + examples: + - 20 + type: number + - description: Timestamp (in milliseconds) to only include Teams created since then. + in: query + name: since + schema: + description: Timestamp (in milliseconds) to only include Teams created since then. + examples: + - 1540095775951 + type: number + - description: Timestamp (in milliseconds) to only include Teams created until then. + in: query + name: until + schema: + description: Timestamp (in milliseconds) to only include Teams created until then. + examples: + - 1540095775951 + type: number + responses: + "200": + content: + application/json: + schema: + description: A paginated list of teams. + properties: + pagination: + $ref: "#/components/schemas/Pagination" + teams: + items: + oneOf: + - $ref: "#/components/schemas/Team" + - $ref: "#/components/schemas/TeamLimited" + type: array + required: + - teams + - pagination + type: object + description: A paginated list of teams. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: List all teams + tags: + - teams + "/v2/teams/{teamId}": + get: + description: Get information for the Team specified by the `teamId` parameter. + operationId: getTeam + parameters: + - in: query + name: slug + schema: + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: path + name: teamId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Team" + description: The requested team + "400": + description: One of the provided values in the request query is invalid. + "403": + description: |- + You do not have permission to access this resource. + Not authorized to access the team. + "404": + description: Team was not found. + security: + - bearerToken: [] + summary: Get a Team + tags: + - teams + patch: + description: Update the information of a Team specified by the `teamId` parameter. The request body should contain the information that will be updated on the Team. + operationId: patchTeam + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: path + name: teamId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + avatar: + description: The hash value of an uploaded image. + format: regex + regex: ^[0-9a-f]{40}$ + type: string + description: + description: A short text that describes the team. + examples: + - Our mission is to make cloud computing accessible to everyone + maxLength: 140 + type: string + emailDomain: + examples: + - example.com + format: regex + regex: \\b((?=[a-z0-9-]{1,63}\\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,63}\\b + type: + - string + - "null" + enablePreviewFeedback: + description: "Enable preview comments: one of on, off or default." + examples: + - on + type: string + migrateExistingEnvVariablesToSensitive: + description: Runs a task that migrates all existing environment variables to sensitive environment variables. + examples: + - false + type: boolean + name: + description: The name of the team. + examples: + - My Team + maxLength: 256 + type: string + previewDeploymentSuffix: + description: Suffix that will be used for all preview deployments. + examples: + - example.dev + format: hostname + type: + - string + - "null" + regenerateInviteCode: + description: Create a new invite code and replace the current one. + examples: + - true + type: boolean + remoteCaching: + additionalProperties: false + description: Whether or not remote caching is enabled for the team + properties: + enabled: + description: Enable or disable remote caching for the team. + examples: + - true + type: boolean + type: object + saml: + additionalProperties: false + properties: + enforced: + description: Require that members of the team use SAML Single Sign-On. + examples: + - true + type: boolean + roles: + additionalProperties: + enum: + - OWNER + - MEMBER + - VIEWER + - DEVELOPER + - BILLING + type: string + type: object + type: object + sensitiveEnvironmentVariablePolicy: + description: "Sensitive environment variable policy: one of on, off or default." + examples: + - on + type: string + slug: + description: A new slug for the team. + examples: + - my-team + type: string + type: object + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Team" + description: "" + "400": + description: One of the provided values in the request body is invalid. + "402": + description: "" + "403": + description: |- + You do not have permission to access this resource. + Not authorized to update the team. Must be an OWNER. + "404": + description: Team was not found. + security: + - bearerToken: [] + summary: Update a Team + tags: + - teams + "/v2/teams/{teamId}/members": + get: + description: Get a paginated list of team members for the provided team. + operationId: getTeamMembers + parameters: + - description: Limit how many teams should be returned + in: query + name: limit + required: false + schema: + description: Limit how many teams should be returned + examples: + - 20 + type: number + - description: Timestamp in milliseconds to only include members added since then. + in: query + name: since + required: false + schema: + description: Timestamp in milliseconds to only include members added since then. + examples: + - 1540095775951 + type: number + - description: Timestamp in milliseconds to only include members added until then. + in: query + name: until + required: false + schema: + description: Timestamp in milliseconds to only include members added until then. + examples: + - 1540095775951 + type: number + - description: Search team members by their name, username, and email. + in: query + name: search + required: false + schema: + description: Search team members by their name, username, and email. + type: string + - description: Only return members with the specified team role. + in: query + name: role + required: false + schema: + description: Only return members with the specified team role. + enum: + - OWNER + - MEMBER + - DEVELOPER + - VIEWER + examples: + - OWNER + type: string + - description: Exclude members who belong to the specified project. + in: query + name: excludeProject + required: false + schema: + description: Exclude members who belong to the specified project. + type: string + - description: Automatically added + in: path + name: teamId + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: Paginated list of members for the team. + properties: + emailInviteCodes: + items: + properties: + createdAt: + type: number + email: + type: string + id: + type: string + isDSyncUser: + type: boolean + role: + enum: + - MEMBER + - OWNER + - VIEWER + - DEVELOPER + - BILLING + type: string + required: + - id + - isDSyncUser + type: object + type: array + members: + items: + properties: + accessRequestedAt: + description: Timestamp in milliseconds for when this team member was accepted by an owner. + examples: + - 1588820733602 + type: number + avatar: + description: ID of the file for the Avatar of this member. + examples: + - 123a6c5209bc3778245d011443644c8d27dc2c50 + type: string + bitbucket: + description: Information about the Bitbucket account of this user. + properties: + accountId: + type: string + email: + type: string + login: + type: string + userId: + type: number + type: object + confirmed: + description: Boolean that indicates if this member was confirmed by an owner. + examples: + - true + type: boolean + createdAt: + description: Timestamp in milliseconds when this member was added. + examples: + - 1588720733602 + type: number + email: + description: The email of this member. + examples: + - jane.doe@example.com + type: string + github: + description: Information about the GitHub account for this user. + properties: + accountId: + type: string + email: + type: string + login: + type: string + userId: + type: number + type: object + gitlab: + description: Information about the GitLab account of this user. + properties: + accountId: + type: string + email: + type: string + login: + type: string + userId: + type: number + type: object + joinedFrom: + description: Map with information about the members origin if they joined by requesting access. + properties: + commitId: + type: string + dsyncConnectedAt: + type: number + dsyncUserId: + type: string + gitUserId: + oneOf: + - type: string + - type: number + gitUserLogin: + type: string + idpUserId: + type: string + origin: + enum: + - import + - gitlab + - bitbucket + - github + - mail + - link + - teams + - saml + - dsync + - feedback + - organization-teams + type: string + repoId: + type: string + repoPath: + type: string + ssoConnectedAt: + type: number + ssoUserId: + type: string + required: + - origin + type: object + name: + description: The name of this user. + examples: + - Jane Doe + type: string + role: + description: Role of this user in the team. + enum: + - MEMBER + - OWNER + - VIEWER + - DEVELOPER + - BILLING + examples: + - OWNER + type: string + uid: + description: The ID of this user. + examples: + - zTuNVUXEAvvnNN3IaqinkyMw + type: string + username: + description: The unique username of this user. + examples: + - jane-doe + type: string + required: + - confirmed + - email + - role + - uid + - username + - createdAt + type: object + type: array + pagination: + properties: + count: + description: Amount of items in the current page. + examples: + - 20 + type: number + hasNext: + type: boolean + next: + description: Timestamp that must be used to request the next page. + examples: + - 1540095775951 + type: + - number + - "null" + prev: + description: Timestamp that must be used to request the previous page. + examples: + - 1540095775951 + type: + - number + - "null" + required: + - hasNext + - count + - next + - prev + type: object + required: + - members + - pagination + type: object + description: Paginated list of members for the team. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: No team was found. + security: + - bearerToken: [] + summary: List team members + tags: + - teams + /v2/user: + get: + description: Retrieves information related to the currently authenticated User. + operationId: getAuthUser + parameters: [] + responses: + "200": + content: + application/json: + schema: + description: Successful response. + properties: + user: + oneOf: + - $ref: "#/components/schemas/AuthUser" + - $ref: "#/components/schemas/AuthUserLimited" + required: + - user + type: object + description: Successful response. + "400": + description: "" + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get the User + tags: + - user + /v3/events: + get: + description: Retrieves a list of "events" generated by the User on Vercel. Events are generated when the User performs a particular action, such as logging in, creating a deployment, and joining a Team (just to name a few). When the `teamId` parameter is supplied, then the events that are returned will be in relation to the Team that was specified. + operationId: listUserEvents + parameters: + - description: Maximum number of items which may be returned. + in: query + name: limit + schema: + description: Maximum number of items which may be returned. + examples: + - 20 + type: number + - description: Timestamp to only include items created since then. + in: query + name: since + schema: + description: Timestamp to only include items created since then. + examples: + - 2019-12-08T10:00:38.976Z + type: string + - description: Timestamp to only include items created until then. + in: query + name: until + schema: + description: Timestamp to only include items created until then. + examples: + - 2019-12-09T23:00:38.976Z + type: string + - description: Comma-delimited list of event \"types\" to filter the results by. + in: query + name: types + schema: + description: Comma-delimited list of event \"types\" to filter the results by. + examples: + - login,team-member-join,domain-buy + type: string + - description: When retrieving events for a Team, the `userId` parameter may be specified to filter events generated by a specific member of the Team. + in: query + name: userId + schema: + description: When retrieving events for a Team, the `userId` parameter may be specified to filter events generated by a specific member of the Team. + examples: + - aeIInYVk59zbFF2SxfyxxmuO + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: Successful response. + properties: + events: + description: Array of events generated by the User. + items: + $ref: "#/components/schemas/UserEvent" + type: array + required: + - events + type: object + description: Successful response. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List User Events + tags: + - user + /v3/secrets: + get: + description: Retrieves the active Vercel secrets for the authenticated user. By default it returns 20 secrets. The rest can be retrieved using the pagination options. The body will contain an entry for each secret. + operationId: getSecrets + parameters: + - description: Filter out secrets based on comma separated secret ids. + in: query + name: id + schema: + deprecated: true + description: Filter out secrets based on comma separated secret ids. + examples: + - sec_RKc5iV0rV3ZSrFrHiruRno7k,sec_fGc5iV0rV3ZSrFrHiruRnouQ + type: string + - description: Filter out secrets that belong to a project. + in: query + name: projectId + schema: + deprecated: true + description: Filter out secrets that belong to a project. + examples: + - prj_2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + pagination: + $ref: "#/components/schemas/Pagination" + secrets: + items: + description: Data representing a secret. + properties: + created: + description: The date when the secret was created. + examples: + - 2021-02-10T13:11:49.180Z + format: date-time + type: string + createdAt: + description: Timestamp for when the secret was created. + examples: + - 1609492210000 + type: number + decryptable: + description: Indicates whether the secret value can be decrypted after it has been created. + examples: + - true + type: boolean + name: + description: The name of the secret. + examples: + - my-api-key + type: string + projectId: + description: The unique identifier of the project which the secret belongs to. + examples: + - prj_2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + teamId: + description: The unique identifier of the team the secret was created for. + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: + - string + - "null" + uid: + description: The unique identifier of the secret. + examples: + - sec_XCG7t7AIHuO2SBA8667zNUiM + type: string + userId: + description: The unique identifier of the user who created the secret. + examples: + - 2qDDuGFTWXBLDNnqZfWPDp1A + type: string + value: + description: The value of the secret. + type: string + required: + - created + - name + - uid + type: object + type: array + required: + - secrets + - pagination + type: object + description: Successful response retrieving a list of secrets. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List secrets + tags: + - secrets + "/v3/secrets/{idOrName}": + get: + description: Retrieves the information for a specific secret by passing either the secret id or name in the URL. + operationId: getSecret + parameters: + - description: The name or the unique identifier to which the secret belongs to. + in: path + name: idOrName + required: true + schema: + description: The name or the unique identifier to which the secret belongs to. + examples: + - sec_RKc5iV0rV3ZSrFrHiruRno7k + type: string + - description: Whether to try to decrypt the value of the secret. Only works if `decryptable` has been set to `true` when the secret was created. + in: query + name: decrypt + required: false + schema: + description: Whether to try to decrypt the value of the secret. Only works if `decryptable` has been set to `true` when the secret was created. + enum: + - "true" + - "false" + examples: + - "true" + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: Data representing a secret. + properties: + created: + description: The date when the secret was created. + examples: + - 2021-02-10T13:11:49.180Z + format: date-time + type: string + createdAt: + description: Timestamp for when the secret was created. + examples: + - 1609492210000 + type: number + decryptable: + description: Indicates whether the secret value can be decrypted after it has been created. + examples: + - true + type: boolean + name: + description: The name of the secret. + examples: + - my-api-key + type: string + projectId: + description: The unique identifier of the project which the secret belongs to. + examples: + - prj_2WjyKQmM8ZnGcJsPWMrHRHrE + type: string + teamId: + description: The unique identifier of the team the secret was created for. + examples: + - team_LLHUOMOoDlqOp8wPE4kFo9pE + type: + - string + - "null" + uid: + description: The unique identifier of the secret. + examples: + - sec_XCG7t7AIHuO2SBA8667zNUiM + type: string + userId: + description: The unique identifier of the user who created the secret. + examples: + - 2qDDuGFTWXBLDNnqZfWPDp1A + type: string + value: + description: The value of the secret. + type: string + required: + - created + - name + - uid + type: object + description: Successful response retrieving a secret. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get a single secret + tags: + - secrets + /v3/user/tokens: + post: + description: Creates and returns a new authentication token for the currently authenticated User. The `bearerToken` property is only provided once, in the response body, so be sure to save it on the client for use with API requests. + operationId: createAuthToken + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + oneOf: + - additionalProperties: false + properties: + expiresAt: + type: number + name: + type: string + required: + - name + type: object + - additionalProperties: false + properties: + clientId: + type: string + expiresAt: + type: number + installationId: + type: string + name: + type: string + type: + enum: + - oauth2-token + required: + - type + - name + type: object + responses: + "200": + content: + application/json: + schema: + description: Successful response. + properties: + bearerToken: + description: The authentication token's actual value. This token is only provided in this response, and can never be retrieved again in the future. Be sure to save it somewhere safe! + examples: + - uRKJSTt0L4RaSkiMj41QTkxM + type: string + token: + $ref: "#/components/schemas/AuthToken" + required: + - token + - bearerToken + type: object + description: Successful response. + "400": + description: One of the provided values in the request body is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Create an Auth Token + tags: + - authentication + "/v3/user/tokens/{tokenId}": + delete: + description: Invalidate an authentication token, such that it will no longer be valid for future HTTP requests. + operationId: deleteAuthToken + parameters: + - description: The identifier of the token to invalidate. The special value \"current\" may be supplied, which invalidates the token that the HTTP request was authenticated with. + in: path + name: tokenId + required: true + schema: + description: The identifier of the token to invalidate. The special value \"current\" may be supplied, which invalidates the token that the HTTP request was authenticated with. + examples: + - 5d9f2ebd38ddca62e5d51e9c1704c72530bdc8bfdd41e782a6687c48399e8391 + type: string + responses: + "200": + content: + application/json: + schema: + description: Authentication token successfully deleted. + properties: + tokenId: + description: The unique identifier of the token that was deleted. + examples: + - 5d9f2ebd38ddca62e5d51e9c1704c72530bdc8bfdd41e782a6687c48399e8391 + type: string + required: + - tokenId + type: object + description: Authentication token successfully deleted. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Token not found with the requested `tokenId`. + security: + - bearerToken: [] + summary: Delete an authentication token + tags: + - authentication + /v4/aliases: + get: + description: Retrieves a list of aliases for the authenticated User or Team. When `domain` is provided, only aliases for that domain will be returned. When `projectId` is provided, it will only return the given project aliases. + operationId: listAliases + parameters: + - description: Get only aliases of the given domain name + in: query + name: domain + schema: + description: Get only aliases of the given domain name + examples: + - my-test-domain.com + items: + type: string + maxItems: 20 + oneOf: + - type: array + - type: string + - description: Get only aliases created after the provided timestamp + in: query + name: from + schema: + deprecated: true + description: Get only aliases created after the provided timestamp + examples: + - 1540095775951 + type: number + - description: Maximum number of aliases to list from a request + in: query + name: limit + schema: + description: Maximum number of aliases to list from a request + examples: + - 10 + type: number + - description: Filter aliases from the given `projectId` + in: query + name: projectId + schema: + description: Filter aliases from the given `projectId` + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: Get aliases created after this JavaScript timestamp + in: query + name: since + schema: + description: Get aliases created after this JavaScript timestamp + examples: + - 1540095775941 + type: number + - description: Get aliases created before this JavaScript timestamp + in: query + name: until + schema: + description: Get aliases created before this JavaScript timestamp + examples: + - 1540095775951 + type: number + - description: Get aliases that would be rolled back for the given deployment + in: query + name: rollbackDeploymentId + schema: + description: Get aliases that would be rolled back for the given deployment + examples: + - dpl_XXX + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + aliases: + items: + properties: + alias: + description: The alias name, it could be a `.vercel.app` subdomain or a custom domain + examples: + - my-alias.vercel.app + type: string + created: + description: The date when the alias was created + examples: + - 2017-04-26T23:00:34.232Z + format: date-time + type: string + createdAt: + description: The date when the alias was created in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + creator: + description: Information of the user who created the alias + properties: + email: + description: Email of the user who created the alias + examples: + - john-doe@gmail.com + type: string + uid: + description: ID of the user who created the alias + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: Username of the user who created the alias + examples: + - john-doe + type: string + required: + - uid + - email + - username + type: object + deletedAt: + description: The date when the alias was deleted in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + deployment: + description: A map with the deployment ID, URL and metadata + properties: + id: + description: The deployment unique identifier + examples: + - dpl_5m8CQaRBm3FnWRW1od3wKTpaECPx + type: string + meta: + description: The deployment metadata + examples: + - {} + type: string + url: + description: The deployment unique URL + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + required: + - id + - url + type: object + deploymentId: + description: The deployment ID + examples: + - dpl_5m8CQaRBm3FnWRW1od3wKTpaECPx + type: + - string + - "null" + projectId: + description: The unique identifier of the project + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: + - string + - "null" + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + redirect: + description: Target destination domain for redirect when the alias is a redirect + type: + - string + - "null" + redirectStatusCode: + description: Status code to be used on redirect + enum: + - 301 + - 302 + - 307 + - 308 + type: + - number + - "null" + uid: + description: The unique identifier of the alias + type: string + updatedAt: + description: The date when the alias was updated in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + required: + - alias + - created + - deploymentId + - projectId + - uid + type: object + type: array + pagination: + $ref: "#/components/schemas/Pagination" + required: + - aliases + - pagination + type: object + description: The paginated list of aliases + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List aliases + tags: + - aliases + "/v4/aliases/{idOrAlias}": + get: + description: Retrieves an Alias for the given host name or alias ID. + operationId: getAlias + parameters: + - description: Get the alias only if it was created after the provided timestamp + in: query + name: from + required: false + schema: + deprecated: true + description: Get the alias only if it was created after the provided timestamp + examples: + - 1540095775951 + type: number + - description: The alias or alias ID to be retrieved + in: path + name: idOrAlias + required: true + schema: + description: The alias or alias ID to be retrieved + examples: + - example.vercel.app + type: string + - description: Get the alias only if it is assigned to the provided project ID + in: query + name: projectId + required: false + schema: + description: Get the alias only if it is assigned to the provided project ID + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: Get the alias only if it was created after this JavaScript timestamp + in: query + name: since + required: false + schema: + description: Get the alias only if it was created after this JavaScript timestamp + examples: + - 1540095775941 + type: number + - description: Get the alias only if it was created before this JavaScript timestamp + in: query + name: until + required: false + schema: + description: Get the alias only if it was created before this JavaScript timestamp + examples: + - 1540095775951 + type: number + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + alias: + description: The alias name, it could be a `.vercel.app` subdomain or a custom domain + examples: + - my-alias.vercel.app + type: string + created: + description: The date when the alias was created + examples: + - 2017-04-26T23:00:34.232Z + format: date-time + type: string + createdAt: + description: The date when the alias was created in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + creator: + description: Information of the user who created the alias + properties: + email: + description: Email of the user who created the alias + examples: + - john-doe@gmail.com + type: string + uid: + description: ID of the user who created the alias + examples: + - 96SnxkFiMyVKsK3pnoHfx3Hz + type: string + username: + description: Username of the user who created the alias + examples: + - john-doe + type: string + required: + - uid + - email + - username + type: object + deletedAt: + description: The date when the alias was deleted in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + deployment: + description: A map with the deployment ID, URL and metadata + properties: + id: + description: The deployment unique identifier + examples: + - dpl_5m8CQaRBm3FnWRW1od3wKTpaECPx + type: string + meta: + description: The deployment metadata + examples: + - {} + type: string + url: + description: The deployment unique URL + examples: + - my-instant-deployment-3ij3cxz9qr.now.sh + type: string + required: + - id + - url + type: object + deploymentId: + description: The deployment ID + examples: + - dpl_5m8CQaRBm3FnWRW1od3wKTpaECPx + type: + - string + - "null" + projectId: + description: The unique identifier of the project + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: + - string + - "null" + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + redirect: + description: Target destination domain for redirect when the alias is a redirect + type: + - string + - "null" + redirectStatusCode: + description: Status code to be used on redirect + enum: + - 301 + - 302 + - 307 + - 308 + type: + - number + - "null" + uid: + description: The unique identifier of the alias + type: string + updatedAt: + description: The date when the alias was updated in milliseconds since the UNIX epoch + examples: + - 1540095775941 + type: number + required: + - alias + - created + - deploymentId + - projectId + - uid + type: object + description: The alias information + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The alias was not found + security: + - bearerToken: [] + summary: Get an Alias + tags: + - aliases + /v4/domains/buy: + post: + description: Allows to purchase the specified domain. + operationId: buyDomain + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + expectedPrice: + description: The price you expect to be charged for the purchase. + examples: + - 10 + type: number + name: + description: The domain name to purchase. + examples: + - example.com + type: string + renew: + description: Indicates whether the domain should be automatically renewed. + examples: + - true + type: boolean + required: + - name + type: object + responses: + "201": + content: + application/json: + schema: + properties: + domain: + properties: + created: + type: number + ns: + items: + type: string + type: array + pending: + type: boolean + uid: + type: string + verified: + type: boolean + required: + - uid + - ns + - verified + - created + - pending + type: object + required: + - domain + type: object + description: Successful response for purchasing a Domain. + "400": + description: One of the provided values in the request body is invalid. + "403": + description: You do not have permission to access this resource. + "409": + description: "" + "429": + description: "" + security: + - bearerToken: [] + summary: Purchase a domain + tags: + - domains + /v4/domains/price: + get: + description: Check the price to purchase a domain and how long a single purchase period is. + operationId: checkDomainPrice + parameters: + - description: The name of the domain for which the price needs to be checked. + in: query + name: name + required: true + schema: + description: The name of the domain for which the price needs to be checked. + examples: + - example.com + type: string + - description: In which status of the domain the price needs to be checked. + in: query + name: type + required: false + schema: + description: In which status of the domain the price needs to be checked. + enum: + - new + - renewal + examples: + - new + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + description: Successful response which returns the price of the domain and the period. + properties: + period: + description: The number of years the domain could be held before paying again. + examples: + - 1 + type: number + price: + description: The domain price in USD. + examples: + - 20 + type: number + required: + - price + - period + type: object + description: Successful response which returns the price of the domain and the period. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Check the price for a domain + tags: + - domains + /v4/domains/status: + get: + description: Check if a domain name is available for purchase. + operationId: checkDomainStatus + parameters: + - description: The name of the domain for which we would like to check the status. + in: query + name: name + required: true + schema: + description: The name of the domain for which we would like to check the status. + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + available: + type: boolean + required: + - available + type: object + description: Successful response checking if a Domain's name is available. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Check a Domain Availability + tags: + - domains + "/v4/domains/{domain}/records": + get: + description: Retrieves a list of DNS records created for a domain name. By default it returns 20 records if no limit is provided. The rest can be retrieved using the pagination options. + operationId: getRecords + parameters: + - in: path + name: domain + required: true + schema: + examples: + - example.com + type: string + - description: Maximum number of records to list from a request. + in: query + name: limit + required: false + schema: + description: Maximum number of records to list from a request. + examples: + - 20 + type: string + - description: Get records created after this JavaScript timestamp. + in: query + name: since + required: false + schema: + description: Get records created after this JavaScript timestamp. + examples: + - 1609499532000 + type: string + - description: Get records created before this JavaScript timestamp. + in: query + name: until + required: false + schema: + description: Get records created before this JavaScript timestamp. + examples: + - 1612264332000 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - type: string + - properties: + records: + items: + properties: + created: + type: + - number + - "null" + createdAt: + type: + - number + - "null" + creator: + type: string + id: + type: string + mxPriority: + type: number + name: + type: string + priority: + type: number + slug: + type: string + type: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + updated: + type: + - number + - "null" + updatedAt: + type: + - number + - "null" + value: + type: string + required: + - id + - slug + - name + - type + - value + - creator + - created + - updated + - createdAt + - updatedAt + type: object + type: array + required: + - records + type: object + - description: Successful response retrieving a list of paginated DNS records. + properties: + pagination: + $ref: "#/components/schemas/Pagination" + records: + items: + properties: + created: + type: + - number + - "null" + createdAt: + type: + - number + - "null" + creator: + type: string + id: + type: string + mxPriority: + type: number + name: + type: string + priority: + type: number + slug: + type: string + type: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + updated: + type: + - number + - "null" + updatedAt: + type: + - number + - "null" + value: + type: string + required: + - id + - slug + - name + - type + - value + - creator + - created + - updated + - createdAt + - updatedAt + type: object + type: array + required: + - records + - pagination + type: object + description: Successful response retrieving a list of paginated DNS records. + "400": + description: One of the provided values in the request query is invalid. + "401": + description: "" + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: List existing DNS records + tags: + - dns + /v5/domains: + get: + description: Retrieves a list of domains registered for the authenticating user. By default it returns the last 20 domains if no limit is provided. + operationId: getDomains + parameters: + - description: Maximum number of domains to list from a request. + in: query + name: limit + schema: + description: Maximum number of domains to list from a request. + examples: + - 20 + type: number + - description: Get domains created after this JavaScript timestamp. + in: query + name: since + schema: + description: Get domains created after this JavaScript timestamp. + examples: + - 1609499532000 + type: number + - description: Get domains created before this JavaScript timestamp. + in: query + name: until + schema: + description: Get domains created before this JavaScript timestamp. + examples: + - 1612264332000 + type: number + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + domains: + items: + properties: + boughtAt: + description: If it was purchased through Vercel, the timestamp in milliseconds when it was purchased. + examples: + - 1613602938882 + type: + - number + - "null" + createdAt: + description: Timestamp in milliseconds when the domain was created in the registry. + examples: + - 1613602938882 + type: number + creator: + description: An object containing information of the domain creator, including the user's id, username, and email. + examples: + - email: demo@example.com + id: ZspSRT4ljIEEmMHgoDwKWDei + username: vercel_user + properties: + customerId: + type: + - string + - "null" + email: + type: string + id: + type: string + isDomainReseller: + type: boolean + username: + type: string + required: + - username + - email + - id + type: object + customNameservers: + description: A list of custom nameservers for the domain to point to. Only applies to domains purchased with Vercel. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + expiresAt: + description: Timestamp in milliseconds at which the domain is set to expire. `null` if not bought with Vercel. + examples: + - 1613602938882 + type: + - number + - "null" + id: + description: The unique identifier of the domain. + examples: + - EmTbe5CEJyTk2yVAHBUWy4A3sRusca3GCwRjTC1bpeVnt1 + type: string + intendedNameservers: + description: A list of the intended nameservers for the domain to point to Vercel DNS. + examples: + - - ns1.vercel-dns.com + - ns2.vercel-dns.com + items: + type: string + type: array + name: + description: The domain name. + examples: + - example.com + type: string + nameservers: + description: A list of the current nameservers of the domain. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + orderedAt: + description: Timestamp in milliseconds at which the domain was ordered. + examples: + - 1613602938882 + type: number + renew: + description: Indicates whether the domain is set to automatically renew. + examples: + - true + type: boolean + serviceType: + description: The type of service the domain is handled by. `external` if the DNS is externally handled, `zeit.world` if handled with Vercel, or `na` if the service is not available. + enum: + - zeit.world + - external + - na + examples: + - zeit.world + type: string + transferStartedAt: + description: If transferred into Vercel, timestamp in milliseconds when the domain transfer was initiated. + examples: + - 1613602938882 + type: number + transferredAt: + description: Timestamp in milliseconds at which the domain was successfully transferred into Vercel. `null` if the transfer is still processing or was never transferred in. + examples: + - 1613602938882 + type: + - number + - "null" + verified: + description: If the domain has the ownership verified. + examples: + - true + type: boolean + required: + - verified + - nameservers + - intendedNameservers + - creator + - createdAt + - id + - name + - expiresAt + - boughtAt + - serviceType + type: object + type: array + pagination: + $ref: "#/components/schemas/Pagination" + required: + - domains + - pagination + type: object + description: Successful response retrieving a list of domains. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "409": + description: "" + security: + - bearerToken: [] + summary: List all the domains + tags: + - domains + post: + description: This endpoint is used for registering a new domain name with Vercel for the authenticating user, and also for initiating a domain transfer request from an external Registrar to Vercel. + operationId: createOrTransferDomain + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + oneOf: + - additionalProperties: false + properties: + method: + description: The domain operation to perform. + examples: + - move-in + type: string + name: + description: The domain name you want to add. + examples: + - example.com + type: string + token: + description: The move-in token from Move Requested email. + examples: + - fdhfr820ad#@FAdlj$$ + type: string + required: + - method + - name + type: object + - additionalProperties: false + properties: + authCode: + description: The authorization code assigned to the domain. + examples: + - fdhfr820ad#@FAdlj$$ + type: string + expectedPrice: + description: The price you expect to be charged for the required 1 year renewal. + examples: + - 8 + type: number + method: + description: The domain operation to perform. + examples: + - transfer-in + type: string + name: + description: The domain name you want to add. + examples: + - example.com + type: string + required: + - method + - name + type: object + - additionalProperties: false + properties: + cdnEnabled: + description: Whether the domain has the Vercel Edge Network enabled or not. + examples: + - true + type: boolean + method: + description: The domain operation to perform. + examples: + - add + type: string + name: + description: The domain name you want to add. + examples: + - example.com + type: string + zone: + type: boolean + required: + - name + type: object + properties: + method: + description: The domain operation to perform. It can be either `add` or `transfer-in`. + examples: + - transfer-in + type: string + responses: + "200": + content: + application/json: + schema: + properties: + domain: + properties: + boughtAt: + description: If it was purchased through Vercel, the timestamp in milliseconds when it was purchased. + examples: + - 1613602938882 + type: + - number + - "null" + createdAt: + description: Timestamp in milliseconds when the domain was created in the registry. + examples: + - 1613602938882 + type: number + creator: + description: An object containing information of the domain creator, including the user's id, username, and email. + examples: + - email: demo@example.com + id: ZspSRT4ljIEEmMHgoDwKWDei + username: vercel_user + properties: + customerId: + type: + - string + - "null" + email: + type: string + id: + type: string + isDomainReseller: + type: boolean + username: + type: string + required: + - username + - email + - id + type: object + customNameservers: + description: A list of custom nameservers for the domain to point to. Only applies to domains purchased with Vercel. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + expiresAt: + description: Timestamp in milliseconds at which the domain is set to expire. `null` if not bought with Vercel. + examples: + - 1613602938882 + type: + - number + - "null" + id: + description: The unique identifier of the domain. + examples: + - EmTbe5CEJyTk2yVAHBUWy4A3sRusca3GCwRjTC1bpeVnt1 + type: string + intendedNameservers: + description: A list of the intended nameservers for the domain to point to Vercel DNS. + examples: + - - ns1.vercel-dns.com + - ns2.vercel-dns.com + items: + type: string + type: array + name: + description: The domain name. + examples: + - example.com + type: string + nameservers: + description: A list of the current nameservers of the domain. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + orderedAt: + description: Timestamp in milliseconds at which the domain was ordered. + examples: + - 1613602938882 + type: number + renew: + description: Indicates whether the domain is set to automatically renew. + examples: + - true + type: boolean + serviceType: + description: The type of service the domain is handled by. `external` if the DNS is externally handled, `zeit.world` if handled with Vercel, or `na` if the service is not available. + enum: + - zeit.world + - external + - na + examples: + - zeit.world + type: string + transferStartedAt: + description: If transferred into Vercel, timestamp in milliseconds when the domain transfer was initiated. + examples: + - 1613602938882 + type: number + transferredAt: + description: Timestamp in milliseconds at which the domain was successfully transferred into Vercel. `null` if the transfer is still processing or was never transferred in. + examples: + - 1613602938882 + type: + - number + - "null" + verified: + description: If the domain has the ownership verified. + examples: + - true + type: boolean + required: + - verified + - nameservers + - intendedNameservers + - creator + - createdAt + - id + - name + - expiresAt + - boughtAt + - serviceType + type: object + required: + - domain + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Register or transfer-in a new Domain + tags: + - domains + "/v5/domains/{domain}": + get: + description: Get information for a single domain in an account or team. + operationId: getDomain + parameters: + - description: The name of the domain. + in: path + name: domain + required: true + schema: + description: The name of the domain. + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + domain: + properties: + boughtAt: + description: If it was purchased through Vercel, the timestamp in milliseconds when it was purchased. + examples: + - 1613602938882 + type: + - number + - "null" + createdAt: + description: Timestamp in milliseconds when the domain was created in the registry. + examples: + - 1613602938882 + type: number + creator: + description: An object containing information of the domain creator, including the user's id, username, and email. + examples: + - email: demo@example.com + id: ZspSRT4ljIEEmMHgoDwKWDei + username: vercel_user + properties: + customerId: + type: + - string + - "null" + email: + type: string + id: + type: string + isDomainReseller: + type: boolean + username: + type: string + required: + - username + - email + - id + type: object + customNameservers: + description: A list of custom nameservers for the domain to point to. Only applies to domains purchased with Vercel. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + expiresAt: + description: Timestamp in milliseconds at which the domain is set to expire. `null` if not bought with Vercel. + examples: + - 1613602938882 + type: + - number + - "null" + id: + description: The unique identifier of the domain. + examples: + - EmTbe5CEJyTk2yVAHBUWy4A3sRusca3GCwRjTC1bpeVnt1 + type: string + intendedNameservers: + description: A list of the intended nameservers for the domain to point to Vercel DNS. + examples: + - - ns1.vercel-dns.com + - ns2.vercel-dns.com + items: + type: string + type: array + name: + description: The domain name. + examples: + - example.com + type: string + nameservers: + description: A list of the current nameservers of the domain. + examples: + - - ns1.nameserver.net + - ns2.nameserver.net + items: + type: string + type: array + orderedAt: + description: Timestamp in milliseconds at which the domain was ordered. + examples: + - 1613602938882 + type: number + renew: + description: Indicates whether the domain is set to automatically renew. + examples: + - true + type: boolean + serviceType: + description: The type of service the domain is handled by. `external` if the DNS is externally handled, `zeit.world` if handled with Vercel, or `na` if the service is not available. + enum: + - zeit.world + - external + - na + examples: + - zeit.world + type: string + suffix: + type: boolean + transferStartedAt: + description: If transferred into Vercel, timestamp in milliseconds when the domain transfer was initiated. + examples: + - 1613602938882 + type: number + transferredAt: + description: Timestamp in milliseconds at which the domain was successfully transferred into Vercel. `null` if the transfer is still processing or was never transferred in. + examples: + - 1613602938882 + type: + - number + - "null" + verified: + description: If the domain has the ownership verified. + examples: + - true + type: boolean + required: + - suffix + - verified + - nameservers + - intendedNameservers + - creator + - createdAt + - id + - name + - expiresAt + - boughtAt + - serviceType + type: object + required: + - domain + type: object + description: Successful response retrieving an information for a specific domains. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get Information for a Single Domain + tags: + - domains + /v5/user/tokens: + get: + description: Retrieve a list of the current User's authentication tokens. + operationId: listAuthTokens + parameters: [] + responses: + "200": + content: + application/json: + schema: + properties: + pagination: + $ref: "#/components/schemas/Pagination" + testingToken: + $ref: "#/components/schemas/AuthToken" + tokens: + items: + $ref: "#/components/schemas/AuthToken" + type: array + required: + - tokens + - pagination + type: object + description: "" + "400": + description: "" + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List Auth Tokens + tags: + - authentication + "/v5/user/tokens/{tokenId}": + get: + description: Retrieve metadata about an authentication token belonging to the currently authenticated User. + operationId: getAuthToken + parameters: + - description: The identifier of the token to retrieve. The special value \"current\" may be supplied, which returns the metadata for the token that the current HTTP request is authenticated with. + in: path + name: tokenId + required: true + schema: + description: The identifier of the token to retrieve. The special value \"current\" may be supplied, which returns the metadata for the token that the current HTTP request is authenticated with. + examples: + - 5d9f2ebd38ddca62e5d51e9c1704c72530bdc8bfdd41e782a6687c48399e8391 + type: string + responses: + "200": + content: + application/json: + schema: + description: Successful response. + properties: + token: + $ref: "#/components/schemas/AuthToken" + required: + - token + type: object + description: Successful response. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Token not found with the requested `tokenId`. + security: + - bearerToken: [] + summary: Get Auth Token Metadata + tags: + - authentication + /v6/deployments: + get: + description: List deployments under the account corresponding to the API token. If a deployment hasn't finished uploading (is incomplete), the `url` property will have a value of `null`. + operationId: getDeployments + parameters: + - description: Name of the deployment. + in: query + name: app + schema: + description: Name of the deployment. + examples: + - docs + type: string + - description: "Gets the deployment created after this Date timestamp. (default: current time)" + in: query + name: from + schema: + deprecated: true + description: "Gets the deployment created after this Date timestamp. (default: current time)" + examples: + - 1612948664566 + type: number + - description: Maximum number of deployments to list from a request. + in: query + name: limit + schema: + description: Maximum number of deployments to list from a request. + examples: + - 10 + type: number + - description: Filter deployments from the given `projectId`. + in: query + name: projectId + schema: + description: Filter deployments from the given `projectId`. + examples: + - QmXGTs7mvAMMC7WW5ebrM33qKG32QK3h4vmQMjmY + type: string + - description: Filter deployments based on the environment. + in: query + name: target + schema: + description: Filter deployments based on the environment. + enum: + - production + - preview + examples: + - production + type: string + - description: "Gets the deployment created before this Date timestamp. (default: current time)" + in: query + name: to + schema: + deprecated: true + description: "Gets the deployment created before this Date timestamp. (default: current time)" + examples: + - 1612948664566 + type: number + - description: Filter out deployments based on users who have created the deployment. + in: query + name: users + schema: + description: Filter out deployments based on users who have created the deployment. + examples: + - kr1PsOIzqEL5Xg6M4VZcZosf,K4amb7K9dAt5R2vBJWF32bmY + type: string + - description: Get Deployments created after this JavaScript timestamp. + in: query + name: since + schema: + description: Get Deployments created after this JavaScript timestamp. + examples: + - 1540095775941 + type: number + - description: Get Deployments created before this JavaScript timestamp. + in: query + name: until + schema: + description: Get Deployments created before this JavaScript timestamp. + examples: + - 1540095775951 + type: number + - description: Filter deployments based on their state (`BUILDING`, `ERROR`, `INITIALIZING`, `QUEUED`, `READY`, `CANCELED`) + in: query + name: state + schema: + description: Filter deployments based on their state (`BUILDING`, `ERROR`, `INITIALIZING`, `QUEUED`, `READY`, `CANCELED`) + examples: + - BUILDING,READY + type: string + - description: Filter deployments based on their rollback candidacy + in: query + name: rollbackCandidate + schema: + description: Filter deployments based on their rollback candidacy + type: boolean + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + deployments: + items: + properties: + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + description: An error object in case aliasing of the deployment failed. + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + buildingAt: + description: Timestamp of when the deployment started building at. + examples: + - 1609492210000 + type: number + checksConclusion: + description: Conclusion for checks + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + description: State of all registered checks + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + description: The ID of Vercel Connect configuration used for this deployment + type: string + created: + description: Timestamp of when the deployment got created. + examples: + - 1609492210000 + type: number + createdAt: + description: Timestamp of when the deployment got created. + examples: + - 1609492210000 + type: number + creator: + description: Metadata information of the user who created the deployment. + properties: + email: + description: The email address of the user. + examples: + - example@example.com + type: string + githubLogin: + description: The GitHub login of the user. + examples: + - johndoe + type: string + gitlabLogin: + description: The GitLab login of the user. + examples: + - johndoe + type: string + uid: + description: The unique identifier of the user. + examples: + - eLrCnEgbKhsHyfbiNR7E8496 + type: string + username: + description: The username of the user. + examples: + - johndoe + type: string + required: + - uid + type: object + inspectorUrl: + description: Vercel URL to inspect the deployment. + examples: + - https://vercel.com/acme/nextjs/J1hXN00qjUeoYfpEEf7dnDtpSiVq + type: + - string + - "null" + isRollbackCandidate: + description: Deployment can be used for instant rollback + type: + - boolean + - "null" + meta: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + name: + description: The name of the deployment. + examples: + - docs + type: string + projectSettings: + description: The project settings which was used for this deployment + properties: + buildCommand: + type: + - string + - "null" + commandForIgnoringBuildStep: + type: + - string + - "null" + createdAt: + type: number + devCommand: + type: + - string + - "null" + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + type: boolean + gitLFS: + type: boolean + installCommand: + type: + - string + - "null" + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + type: + - string + - "null" + publicSource: + type: + - boolean + - "null" + rootDirectory: + type: + - string + - "null" + serverlessFunctionRegion: + type: + - string + - "null" + skipGitConnectDuringLink: + type: boolean + sourceFilesOutsideRootDirectory: + type: boolean + type: object + ready: + description: Timestamp of when the deployment got ready. + examples: + - 1609492210000 + type: number + source: + description: The source of the deployment. + enum: + - cli + - git + - import + - import/repo + - clone/repo + examples: + - cli + type: string + state: + description: In which state is the deployment. + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + examples: + - READY + type: string + target: + description: On which environment has the deployment been deployed to. + enum: + - production + - staging + examples: + - production + type: + - string + - "null" + type: + description: The type of the deployment. + enum: + - LAMBDAS + examples: + - LAMBDAS + type: string + uid: + description: The unique identifier of the deployment. + examples: + - dpl_2euZBFqxYdDMDG1jTrHFnNZ2eUVa + type: string + url: + description: The URL of the deployment. + examples: + - docs-9jaeg38me.vercel.app + type: string + required: + - uid + - name + - url + - created + - type + - creator + - inspectorUrl + type: object + type: array + pagination: + $ref: "#/components/schemas/Pagination" + required: + - pagination + - deployments + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: List deployments + tags: + - deployments + "/v6/deployments/{id}/files": + get: + description: Allows to retrieve the file structure of a deployment by supplying the deployment unique identifier. + operationId: listDeploymentFiles + parameters: + - description: The unique deployment identifier + in: path + name: id + required: true + schema: + description: The unique deployment identifier + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/FileTree" + type: array + description: Retrieved the file tree successfully + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + File tree not found + Deployment not found + security: + - bearerToken: [] + summary: List Deployment Files + tags: + - deployments + "/v6/deployments/{id}/files/{fileId}": + get: + description: Allows to retrieve the content of a file by supplying the file identifier and the deployment unique identifier. The response body will contain the raw content of the file. + operationId: getDeploymentFileContents + parameters: + - description: The unique deployment identifier + in: path + name: id + required: true + schema: + description: The unique deployment identifier + type: string + - description: The unique file identifier + in: path + name: fileId + required: true + schema: + description: The unique file identifier + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + File not found + Deployment not found + security: + - bearerToken: [] + summary: Get Deployment File Contents + tags: + - deployments + "/v6/domains/{domain}": + delete: + description: Delete a previously registered domain name from Vercel. Deleting a domain will automatically remove any associated aliases. + operationId: deleteDomain + parameters: + - description: The name of the domain. + in: path + name: domain + required: true + schema: + description: The name of the domain. + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + uid: + type: string + required: + - uid + type: object + description: Successful response removing a domain. + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Remove a domain by name + tags: + - domains + "/v6/domains/{domain}/config": + get: + description: Get a Domain's configuration. + operationId: getDomainConfig + parameters: + - description: The name of the domain. + in: path + name: domain + required: true + schema: + description: The name of the domain. + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + acceptedChallenges: + description: Which challenge types the domain can use for issuing certs. + items: + description: Which challenge types the domain can use for issuing certs. + enum: + - dns-01 + - http-01 + type: string + type: array + configuredBy: + description: "How we see the domain's configuration. - `CNAME`: Domain has a CNAME pointing to Vercel. - `A`: Domain's A record is resolving to Vercel. - `http`: Domain is resolving to Vercel but may be behind a Proxy. - `null`: Domain is not resolving to Vercel." + enum: + - CNAME + - A + - http + type: + - string + - "null" + misconfigured: + description: Whether or not the domain is configured AND we can automatically generate a TLS certificate. + type: boolean + required: + - misconfigured + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get a Domain's configuration + tags: + - domains + /v7/certs: + post: + description: Issue a new cert + operationId: issueCert + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + cns: + description: The common names the cert should be issued for + items: + type: string + type: array + type: object + responses: + "200": + content: + application/json: + schema: + properties: + autoRenew: + type: boolean + cns: + items: + type: string + type: array + createdAt: + type: number + expiresAt: + type: number + id: + type: string + required: + - id + - createdAt + - expiresAt + - autoRenew + - cns + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "429": + description: "" + "449": + description: "" + "500": + description: "" + security: + - bearerToken: [] + summary: Issue a new cert + tags: + - certs + put: + description: Upload a cert + operationId: uploadCert + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + ca: + description: The certificate authority + type: string + cert: + description: The certificate + type: string + key: + description: The certificate key + type: string + skipValidation: + description: Skip validation of the certificate + type: boolean + required: + - ca + - key + - cert + type: object + responses: + "200": + content: + application/json: + schema: + properties: + autoRenew: + type: boolean + cns: + items: + type: string + type: array + createdAt: + type: number + expiresAt: + type: number + id: + type: string + required: + - id + - createdAt + - expiresAt + - autoRenew + - cns + type: object + description: "" + "400": + description: One of the provided values in the request body is invalid. + "402": + description: |- + This feature is only available for Enterprise customers. + This feature is optionally available for advanced use cases. Contact Sales: https://vercel.com/contact/sales + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Upload a cert + tags: + - certs + "/v7/certs/{id}": + delete: + description: Remove cert + operationId: removeCert + parameters: + - description: The cert id to remove + in: path + name: id + required: true + schema: + description: The cert id to remove + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Remove cert + tags: + - certs + get: + description: Get cert by id + operationId: getCertById + parameters: + - description: The cert id + in: path + name: id + required: true + schema: + description: The cert id + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + autoRenew: + type: boolean + cns: + items: + type: string + type: array + createdAt: + type: number + expiresAt: + type: number + id: + type: string + required: + - id + - createdAt + - expiresAt + - autoRenew + - cns + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + security: + - bearerToken: [] + summary: Get cert by id + tags: + - certs + /v8/artifacts: + post: + description: Query information about an array of artifacts. + operationId: artifactQuery + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + hashes: + description: artifact hashes + items: + type: string + type: array + required: + - hashes + type: object + responses: + "400": + description: One of the provided values in the request body is invalid. + "401": + description: |- + Invalid token + The request is missing an authentication token + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + The customer has reached their spend cap limit and has been paused. An owner can disable the cap or raise the limit in settings. + The Remote Caching usage limit has been reached for this account for this billing cycle. + Remote Caching has been disabled for this team or user. An owner can enable it in the billing settings. + You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Query information about an artifact + tags: + - artifacts + /v8/artifacts/events: + post: + description: Records an artifacts cache usage event. The body of this request is an array of cache usage events. The supported event types are `HIT` and `MISS`. The source is either `LOCAL` the cache event was on the users filesystem cache or `REMOTE` if the cache event is for a remote cache. When the event is a `HIT` the request also accepts a number `duration` which is the time taken to generate the artifact in the cache. + operationId: recordEvents + parameters: + - description: The continuous integration or delivery environment where this artifact is downloaded. + in: header + name: x-artifact-client-ci + schema: + description: The continuous integration or delivery environment where this artifact is downloaded. + examples: + - VERCEL + maxLength: 50 + type: string + - description: 1 if the client is an interactive shell. Otherwise 0 + in: header + name: x-artifact-client-interactive + schema: + description: 1 if the client is an interactive shell. Otherwise 0 + examples: + - 0 + maximum: 1 + minimum: 0 + type: integer + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + items: + additionalProperties: false + properties: + duration: + description: The time taken to generate the artifact. This should be sent as a body parameter on `HIT` events. + examples: + - 400 + type: number + event: + description: One of `HIT` or `MISS`. `HIT` specifies that a cached artifact for `hash` was found in the cache. `MISS` specifies that a cached artifact with `hash` was not found. + enum: + - HIT + - MISS + type: string + hash: + description: The artifact hash + examples: + - 12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + sessionId: + description: A UUID (universally unique identifer) for the session that generated this event. + type: string + source: + description: One of `LOCAL` or `REMOTE`. `LOCAL` specifies that the cache event was from the user's filesystem cache. `REMOTE` specifies that the cache event is from a remote cache. + enum: + - LOCAL + - REMOTE + type: string + required: + - sessionId + - source + - hash + - event + type: object + type: array + responses: + "200": + description: Success. Event recorded. + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the headers is invalid + "401": + description: |- + Invalid token + The request is missing an authentication token + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + The customer has reached their spend cap limit and has been paused. An owner can disable the cap or raise the limit in settings. + The Remote Caching usage limit has been reached for this account for this billing cycle. + Remote Caching has been disabled for this team or user. An owner can enable it in the billing settings. + You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Record an artifacts cache usage event + tags: + - artifacts + /v8/artifacts/status: + get: + description: Check the status of Remote Caching for this principal. Returns a JSON-encoded status indicating if Remote Caching is enabled, disabled, or disabled due to usage limits. + operationId: status + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "400": + description: "" + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Get status of Remote Caching for this principal + tags: + - artifacts + "/v8/artifacts/{hash}": + get: + description: Downloads a cache artifact indentified by its `hash` specified on the request path. The artifact is downloaded as an octet-stream. The client should verify the content-length header and response body. + operationId: downloadArtifact + parameters: + - description: The continuous integration or delivery environment where this artifact is downloaded. + in: header + name: x-artifact-client-ci + schema: + description: The continuous integration or delivery environment where this artifact is downloaded. + examples: + - VERCEL + maxLength: 50 + type: string + - description: 1 if the client is an interactive shell. Otherwise 0 + in: header + name: x-artifact-client-interactive + schema: + description: 1 if the client is an interactive shell. Otherwise 0 + examples: + - 0 + maximum: 1 + minimum: 0 + type: integer + - description: The artifact hash + in: path + name: hash + required: true + schema: + description: The artifact hash + examples: + - 12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "400": + description: |- + One of the provided values in the request query is invalid. + One of the provided values in the headers is invalid + "401": + description: |- + Invalid token + The request is missing an authentication token + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + The customer has reached their spend cap limit and has been paused. An owner can disable the cap or raise the limit in settings. + The Remote Caching usage limit has been reached for this account for this billing cycle. + Remote Caching has been disabled for this team or user. An owner can enable it in the billing settings. + You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Download a cache artifact + tags: + - artifacts + head: + description: Check that a cache artifact with the given `hash` exists. This request returns response headers only and is equivalent to a `GET` request to this endpoint where the response contains no body. + operationId: artifactExists + parameters: + - description: The artifact hash + in: path + name: hash + required: true + schema: + description: The artifact hash + examples: + - 12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "400": + description: One of the provided values in the request query is invalid. + "401": + description: |- + Invalid token + The request is missing an authentication token + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + The customer has reached their spend cap limit and has been paused. An owner can disable the cap or raise the limit in settings. + The Remote Caching usage limit has been reached for this account for this billing cycle. + Remote Caching has been disabled for this team or user. An owner can enable it in the billing settings. + You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Check if a cache artifact exists + tags: + - artifacts + put: + description: Uploads a cache artifact identified by the `hash` specified on the path. The cache artifact can then be downloaded with the provided `hash`. + operationId: uploadArtifact + parameters: + - description: The artifact size in bytes + in: header + name: Content-Length + required: true + schema: + description: The artifact size in bytes + type: number + - description: The time taken to generate the uploaded artifact in milliseconds. + in: header + name: x-artifact-duration + required: false + schema: + description: The time taken to generate the uploaded artifact in milliseconds. + examples: + - 400 + type: number + - description: The continuous integration or delivery environment where this artifact was generated. + in: header + name: x-artifact-client-ci + required: false + schema: + description: The continuous integration or delivery environment where this artifact was generated. + examples: + - VERCEL + maxLength: 50 + type: string + - description: 1 if the client is an interactive shell. Otherwise 0 + in: header + name: x-artifact-client-interactive + required: false + schema: + description: 1 if the client is an interactive shell. Otherwise 0 + examples: + - 0 + maximum: 1 + minimum: 0 + type: integer + - description: The base64 encoded tag for this artifact. The value is sent back to clients when the artifact is downloaded as the header `x-artifact-tag` + in: header + name: x-artifact-tag + required: false + schema: + description: The base64 encoded tag for this artifact. The value is sent back to clients when the artifact is downloaded as the header `x-artifact-tag` + examples: + - Tc0BmHvJYMIYJ62/zx87YqO0Flxk+5Ovip25NY825CQ= + maxLength: 600 + type: string + - description: The artifact hash + in: path + name: hash + required: true + schema: + description: The artifact hash + examples: + - 12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/octet-stream: + schema: {} + responses: + "400": + description: |- + One of the provided values in the request query is invalid. + One of the provided values in the headers is invalid + "401": + description: |- + Invalid token + The request is missing an authentication token + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: |- + The customer has reached their spend cap limit and has been paused. An owner can disable the cap or raise the limit in settings. + The Remote Caching usage limit has been reached for this account for this billing cycle. + Remote Caching has been disabled for this team or user. An owner can enable it in the billing settings. + You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Upload a cache artifact + tags: + - artifacts + /v9/projects: + get: + description: Allows to retrieve the list of projects of the authenticated user. The list will be paginated and the provided query parameters allow filtering the returned projects. + operationId: getProjects + parameters: + - description: Query only projects updated after the given timestamp + in: query + name: from + schema: + description: Query only projects updated after the given timestamp + type: string + - description: Specifies whether PRs from Git forks should require a team member's authorization before it can be deployed + in: query + name: gitForkProtection + schema: + description: Specifies whether PRs from Git forks should require a team member's authorization before it can be deployed + enum: + - "1" + - "0" + examples: + - "1" + type: string + - description: Limit the number of projects returned + in: query + name: limit + schema: + description: Limit the number of projects returned + type: string + - description: Search projects by the name field + in: query + name: search + schema: + description: Search projects by the name field + type: string + - description: Filter results by repo. Also used for project count + in: query + name: repo + schema: + description: Filter results by repo. Also used for project count + type: string + - description: Filter results by Repository ID. + in: query + name: repoId + schema: + description: Filter results by Repository ID. + type: string + - description: Filter results by Repository URL. + in: query + name: repoUrl + schema: + description: Filter results by Repository URL. + examples: + - https://github.com/vercel/next.js + type: string + - description: Filter results by excluding those projects that belong to a repo + in: query + name: excludeRepos + schema: + description: Filter results by excluding those projects that belong to a repo + type: string + - description: Filter results by connected Edge Config ID + in: query + name: edgeConfigId + schema: + description: Filter results by connected Edge Config ID + type: string + - description: Filter results by connected Edge Config Token ID + in: query + name: edgeConfigTokenId + schema: + description: Filter results by connected Edge Config Token ID + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + pagination: + $ref: "#/components/schemas/Pagination" + projects: + items: + properties: + accountId: + type: string + analytics: + properties: + canceledAt: + type: + - number + - "null" + disabledAt: + type: number + enabledAt: + type: number + id: + type: string + paidAt: + type: number + sampleRatePercent: + type: + - number + - "null" + spendLimitInDollars: + type: + - number + - "null" + required: + - id + - canceledAt + - disabledAt + - enabledAt + type: object + autoExposeSystemEnvs: + type: boolean + buildCommand: + type: + - string + - "null" + commandForIgnoringBuildStep: + type: + - string + - "null" + connectBuildsEnabled: + type: boolean + connectConfigurationId: + type: + - string + - "null" + createdAt: + type: number + devCommand: + type: + - string + - "null" + directoryListing: + type: boolean + enablePreviewFeedback: + type: + - boolean + - "null" + env: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + type: array + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + type: boolean + gitLFS: + type: boolean + hasActiveBranches: + type: boolean + hasFloatingAliases: + type: boolean + id: + type: string + installCommand: + type: + - string + - "null" + lastRollbackTarget: + properties: + fromDeploymentId: + type: string + jobStatus: + enum: + - succeeded + - failed + - skipped + - pending + - in-progress + type: string + requestedAt: + type: number + toDeploymentId: + type: string + required: + - fromDeploymentId + - toDeploymentId + - jobStatus + - requestedAt + type: + - object + - "null" + latestDeployments: + items: + properties: + alias: + items: + type: string + type: array + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + automaticAliases: + items: + type: string + type: array + buildingAt: + type: number + builds: + items: + properties: + dest: + type: string + src: + type: string + use: + type: string + required: + - use + type: object + type: array + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + type: string + createdAt: + type: number + createdIn: + type: string + creator: + properties: + email: + type: string + githubLogin: + type: string + gitlabLogin: + type: string + uid: + type: string + username: + type: string + required: + - email + - uid + - username + type: + - object + - "null" + deploymentHostname: + type: string + forced: + type: boolean + id: + type: string + meta: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + monorepoManager: + type: + - string + - "null" + name: + type: string + plan: + enum: + - hobby + - enterprise + - pro + - oss + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + private: + type: boolean + readyAt: + type: number + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + type: string + requestedAt: + type: number + target: + type: + - string + - "null" + teamId: + type: + - string + - "null" + type: + enum: + - LAMBDAS + type: string + url: + type: string + userId: + type: string + withCache: + type: boolean + required: + - createdAt + - createdIn + - creator + - deploymentHostname + - name + - id + - plan + - private + - readyState + - type + - url + - userId + type: object + type: array + link: + oneOf: + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + org: + type: string + productionBranch: + type: string + repo: + type: string + repoId: + type: number + sourceless: + type: boolean + type: + enum: + - github + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + productionBranch: + type: string + projectId: + type: string + projectName: + type: string + projectNameWithNamespace: + type: string + projectNamespace: + type: string + projectUrl: + type: string + sourceless: + type: boolean + type: + enum: + - gitlab + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + name: + type: string + owner: + type: string + productionBranch: + type: string + slug: + type: string + sourceless: + type: boolean + type: + enum: + - bitbucket + type: string + updatedAt: + type: number + uuid: + type: string + workspaceUuid: + type: string + required: + - deployHooks + type: object + live: + type: boolean + name: + type: string + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + type: + - string + - "null" + passwordProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + permissions: + properties: + Monitoring: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasGlobal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProject: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsSampling: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsUsage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + auditLog: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingAddress: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInformation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoice: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceEmailRecipient: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceLanguage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPurchaseOrder: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingTaxId: + items: + $ref: "#/components/schemas/ACLAction" + type: array + blob: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifact: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifactUsageEvent: + items: + $ref: "#/components/schemas/ACLAction" + type: array + concurrentBuilds: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connect: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfigurationLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deployment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheck: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckReRunFromProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPrivate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentProductionGit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentRollback: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAcceptDelegation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAuthCodes: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCertificate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCheckConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainRecord: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainTransferIn: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigItem: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigToken: + items: + $ref: "#/components/schemas/ACLAction" + type: array + endpointVerification: + items: + $ref: "#/components/schemas/ACLAction" + type: array + event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + fileUpload: + items: + $ref: "#/components/schemas/ACLAction" + type: array + gitRepository: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationProjects: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationVercelConfigurationOverride: + items: + $ref: "#/components/schemas/ACLAction" + type: array + ipBlocking: + items: + $ref: "#/components/schemas/ACLAction" + type: array + job: + items: + $ref: "#/components/schemas/ACLAction" + type: array + logDrain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringChart: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringQuery: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainExpire: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainMoved: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainRenewal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainUnverified: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationPaymentFailed: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationSpendCap: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationUsageAlert: + items: + $ref: "#/components/schemas/ACLAction" + type: array + openTelemetryEndpoint: + items: + $ref: "#/components/schemas/ACLAction" + type: array + passwordProtection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + paymentMethod: + items: + $ref: "#/components/schemas/ACLAction" + type: array + permissions: + items: + $ref: "#/components/schemas/ACLAction" + type: array + postgres: + items: + $ref: "#/components/schemas/ACLAction" + type: array + previewDeploymentSuffix: + items: + $ref: "#/components/schemas/ACLAction" + type: array + proTrialOnboarding: + items: + $ref: "#/components/schemas/ACLAction" + type: array + project: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDeploymentHook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsUnownedByIntegration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectIntegrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectMember: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + rateLimit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + redis: + items: + $ref: "#/components/schemas/ACLAction" + type: array + remoteCaching: + items: + $ref: "#/components/schemas/ACLAction" + type: array + samlConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + secret: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sensitiveEnvironmentVariablePolicy: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapState: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCaseComment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + team: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamAccessRequest: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamFellowMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInvite: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInviteCode: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamJoin: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembershipDisconnectSAML: + items: + $ref: "#/components/schemas/ACLAction" + type: array + token: + items: + $ref: "#/components/schemas/ACLAction" + type: array + usage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + user: + items: + $ref: "#/components/schemas/ACLAction" + type: array + userConnection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalyticsPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook-event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + type: object + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + publicSource: + type: + - boolean + - "null" + rootDirectory: + type: + - string + - "null" + serverlessFunctionRegion: + type: + - string + - "null" + skipGitConnectDuringLink: + type: boolean + sourceFilesOutsideRootDirectory: + type: boolean + ssoProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + targets: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + transferCompletedAt: + type: number + transferStartedAt: + type: number + transferToAccountId: + type: string + transferredFromAccountId: + type: string + updatedAt: + type: number + required: + - accountId + - directoryListing + - id + - name + - nodeVersion + type: object + type: array + required: + - projects + - pagination + type: object + description: The paginated list of projects + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Retrieve a list of projects + tags: + - projects + post: + description: Allows to create a new project with the provided configuration. It only requires the project `name` but more configuration can be provided to override the defaults. + operationId: createProject + parameters: + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + buildCommand: + description: The build command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + commandForIgnoringBuildStep: + maxLength: 256 + type: + - string + - "null" + devCommand: + description: The dev command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + environmentVariables: + description: Collection of ENV Variables the Project will use + items: + properties: + gitBranch: + description: The git branch of the environment variable + examples: + - feature-1 + maxLength: 250 + type: string + key: + description: Name of the ENV variable + type: string + target: + description: Deployment Target or Targets in which the ENV variable will be used + oneOf: + - enum: + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Productio + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Previe + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Developmen + - items: + enum: + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Productio + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Previe + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Developmen + type: array + type: + description: Type of the ENV variable + enum: + - system + - secret + - encrypted + - plain + type: string + value: + description: Value for the ENV variable + type: string + required: + - key + - value + - target + type: object + type: array + framework: + description: The framework that is being used for this project. When `null` is used no framework is selected + enum: + - null + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + gitRepository: + description: The Git Repository that will be connected to the project. When this is defined, any pushes to the specified connected Git Repository will be automatically deployed + properties: + repo: + description: 'The name of the git repository. For example: \"vercel/next.js\"' + type: string + type: + description: The Git Provider of the repository + enum: + - github + - gitlab + - bitbucket + required: + - type + - repo + type: object + installCommand: + description: The install command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + name: + description: The desired name for the project + examples: + - a-project-name + maxLength: 100 + pattern: ^[a-z0-9]([a-z0-9]|-[a-z0-9])*$ + type: string + outputDirectory: + description: The output directory of the project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + publicSource: + description: Specifies whether the source code and logs of the deployments for this project should be public or not + type: + - boolean + - "null" + rootDirectory: + description: The name of a directory or relative path to the source code of your project. When `null` is used it will default to the project root + maxLength: 256 + type: + - string + - "null" + serverlessFunctionRegion: + description: The region to deploy Serverless Functions in this project + maxLength: 4 + type: + - string + - "null" + skipGitConnectDuringLink: + deprecated: true + description: Opts-out of the message prompting a CLI user to connect a Git repository in `vercel link`. + type: boolean + required: + - name + type: object + responses: + "200": + content: + application/json: + schema: + properties: + accountId: + type: string + analytics: + properties: + canceledAt: + type: + - number + - "null" + disabledAt: + type: number + enabledAt: + type: number + id: + type: string + paidAt: + type: number + sampleRatePercent: + type: + - number + - "null" + spendLimitInDollars: + type: + - number + - "null" + required: + - id + - canceledAt + - disabledAt + - enabledAt + type: object + autoExposeSystemEnvs: + type: boolean + buildCommand: + type: + - string + - "null" + commandForIgnoringBuildStep: + type: + - string + - "null" + connectBuildsEnabled: + type: boolean + connectConfigurationId: + type: + - string + - "null" + createdAt: + type: number + devCommand: + type: + - string + - "null" + directoryListing: + type: boolean + enablePreviewFeedback: + type: + - boolean + - "null" + env: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + type: array + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + type: boolean + gitLFS: + type: boolean + hasActiveBranches: + type: boolean + hasFloatingAliases: + type: boolean + id: + type: string + installCommand: + type: + - string + - "null" + lastRollbackTarget: + properties: + fromDeploymentId: + type: string + jobStatus: + enum: + - succeeded + - failed + - skipped + - pending + - in-progress + type: string + requestedAt: + type: number + toDeploymentId: + type: string + required: + - fromDeploymentId + - toDeploymentId + - jobStatus + - requestedAt + type: + - object + - "null" + latestDeployments: + items: + properties: + alias: + items: + type: string + type: array + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + automaticAliases: + items: + type: string + type: array + buildingAt: + type: number + builds: + items: + properties: + dest: + type: string + src: + type: string + use: + type: string + required: + - use + type: object + type: array + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + type: string + createdAt: + type: number + createdIn: + type: string + creator: + properties: + email: + type: string + githubLogin: + type: string + gitlabLogin: + type: string + uid: + type: string + username: + type: string + required: + - email + - uid + - username + type: + - object + - "null" + deploymentHostname: + type: string + forced: + type: boolean + id: + type: string + meta: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + monorepoManager: + type: + - string + - "null" + name: + type: string + plan: + enum: + - hobby + - enterprise + - pro + - oss + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + private: + type: boolean + readyAt: + type: number + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + type: string + requestedAt: + type: number + target: + type: + - string + - "null" + teamId: + type: + - string + - "null" + type: + enum: + - LAMBDAS + type: string + url: + type: string + userId: + type: string + withCache: + type: boolean + required: + - createdAt + - createdIn + - creator + - deploymentHostname + - name + - id + - plan + - private + - readyState + - type + - url + - userId + type: object + type: array + link: + oneOf: + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + org: + type: string + productionBranch: + type: string + repo: + type: string + repoId: + type: number + sourceless: + type: boolean + type: + enum: + - github + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + productionBranch: + type: string + projectId: + type: string + projectName: + type: string + projectNameWithNamespace: + type: string + projectNamespace: + type: string + projectUrl: + type: string + sourceless: + type: boolean + type: + enum: + - gitlab + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + name: + type: string + owner: + type: string + productionBranch: + type: string + slug: + type: string + sourceless: + type: boolean + type: + enum: + - bitbucket + type: string + updatedAt: + type: number + uuid: + type: string + workspaceUuid: + type: string + required: + - deployHooks + type: object + live: + type: boolean + name: + type: string + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + type: + - string + - "null" + passwordProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + permissions: + properties: + Monitoring: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasGlobal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProject: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsSampling: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsUsage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + auditLog: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingAddress: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInformation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoice: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceEmailRecipient: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceLanguage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPurchaseOrder: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingTaxId: + items: + $ref: "#/components/schemas/ACLAction" + type: array + blob: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifact: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifactUsageEvent: + items: + $ref: "#/components/schemas/ACLAction" + type: array + concurrentBuilds: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connect: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfigurationLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deployment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheck: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckReRunFromProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPrivate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentProductionGit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentRollback: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAcceptDelegation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAuthCodes: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCertificate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCheckConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainRecord: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainTransferIn: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigItem: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigToken: + items: + $ref: "#/components/schemas/ACLAction" + type: array + endpointVerification: + items: + $ref: "#/components/schemas/ACLAction" + type: array + event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + fileUpload: + items: + $ref: "#/components/schemas/ACLAction" + type: array + gitRepository: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationProjects: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationVercelConfigurationOverride: + items: + $ref: "#/components/schemas/ACLAction" + type: array + ipBlocking: + items: + $ref: "#/components/schemas/ACLAction" + type: array + job: + items: + $ref: "#/components/schemas/ACLAction" + type: array + logDrain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringChart: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringQuery: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainExpire: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainMoved: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainRenewal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainUnverified: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationPaymentFailed: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationSpendCap: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationUsageAlert: + items: + $ref: "#/components/schemas/ACLAction" + type: array + openTelemetryEndpoint: + items: + $ref: "#/components/schemas/ACLAction" + type: array + passwordProtection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + paymentMethod: + items: + $ref: "#/components/schemas/ACLAction" + type: array + permissions: + items: + $ref: "#/components/schemas/ACLAction" + type: array + postgres: + items: + $ref: "#/components/schemas/ACLAction" + type: array + previewDeploymentSuffix: + items: + $ref: "#/components/schemas/ACLAction" + type: array + proTrialOnboarding: + items: + $ref: "#/components/schemas/ACLAction" + type: array + project: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDeploymentHook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsUnownedByIntegration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectIntegrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectMember: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + rateLimit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + redis: + items: + $ref: "#/components/schemas/ACLAction" + type: array + remoteCaching: + items: + $ref: "#/components/schemas/ACLAction" + type: array + samlConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + secret: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sensitiveEnvironmentVariablePolicy: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapState: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCaseComment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + team: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamAccessRequest: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamFellowMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInvite: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInviteCode: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamJoin: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembershipDisconnectSAML: + items: + $ref: "#/components/schemas/ACLAction" + type: array + token: + items: + $ref: "#/components/schemas/ACLAction" + type: array + usage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + user: + items: + $ref: "#/components/schemas/ACLAction" + type: array + userConnection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalyticsPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook-event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + type: object + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + publicSource: + type: + - boolean + - "null" + rootDirectory: + type: + - string + - "null" + serverlessFunctionRegion: + type: + - string + - "null" + skipGitConnectDuringLink: + type: boolean + sourceFilesOutsideRootDirectory: + type: boolean + ssoProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + targets: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + transferCompletedAt: + type: number + transferStartedAt: + type: number + transferToAccountId: + type: string + transferredFromAccountId: + type: string + updatedAt: + type: number + required: + - accountId + - directoryListing + - id + - name + - nodeVersion + type: object + description: The project was successfuly created + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The Bitbucket Webhook for the project link could not be created + The Gitlab Webhook for the project link could not be created + "402": + description: |- + The account was soft-blocked for an unhandled reason. + The account is missing a payment so payment method must be updated + "403": + description: You do not have permission to access this resource. + "409": + description: A project with the provided name already exists. + security: + - bearerToken: [] + summary: Create a new project + tags: + - projects + "/v9/projects/{idOrName}": + delete: + description: Delete a specific project by passing either the project `id` or `name` in the URL. + operationId: deleteProject + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "204": + description: The project was successfuly removed + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: "" + "409": + description: "" + security: + - bearerToken: [] + summary: Delete a Project + tags: + - projects + get: + description: Get the information for a specific project by passing either the project `id` or `name` in the URL. + operationId: getProject + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + oneOf: + - type: string + - type: boolean + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + accountId: + type: string + analytics: + properties: + canceledAt: + type: + - number + - "null" + disabledAt: + type: number + enabledAt: + type: number + id: + type: string + paidAt: + type: number + sampleRatePercent: + type: + - number + - "null" + spendLimitInDollars: + type: + - number + - "null" + required: + - id + - canceledAt + - disabledAt + - enabledAt + type: object + autoExposeSystemEnvs: + type: boolean + buildCommand: + type: + - string + - "null" + commandForIgnoringBuildStep: + type: + - string + - "null" + connectBuildsEnabled: + type: boolean + connectConfigurationId: + type: + - string + - "null" + createdAt: + type: number + devCommand: + type: + - string + - "null" + directoryListing: + type: boolean + enablePreviewFeedback: + type: + - boolean + - "null" + env: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + type: array + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + type: boolean + gitLFS: + type: boolean + hasActiveBranches: + type: boolean + hasFloatingAliases: + type: boolean + id: + type: string + installCommand: + type: + - string + - "null" + lastRollbackTarget: + properties: + fromDeploymentId: + type: string + jobStatus: + enum: + - succeeded + - failed + - skipped + - pending + - in-progress + type: string + requestedAt: + type: number + toDeploymentId: + type: string + required: + - fromDeploymentId + - toDeploymentId + - jobStatus + - requestedAt + type: + - object + - "null" + latestDeployments: + items: + properties: + alias: + items: + type: string + type: array + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + automaticAliases: + items: + type: string + type: array + buildingAt: + type: number + builds: + items: + properties: + dest: + type: string + src: + type: string + use: + type: string + required: + - use + type: object + type: array + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + type: string + createdAt: + type: number + createdIn: + type: string + creator: + properties: + email: + type: string + githubLogin: + type: string + gitlabLogin: + type: string + uid: + type: string + username: + type: string + required: + - email + - uid + - username + type: + - object + - "null" + deploymentHostname: + type: string + forced: + type: boolean + id: + type: string + meta: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + monorepoManager: + type: + - string + - "null" + name: + type: string + plan: + enum: + - hobby + - enterprise + - pro + - oss + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + private: + type: boolean + readyAt: + type: number + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + type: string + requestedAt: + type: number + target: + type: + - string + - "null" + teamId: + type: + - string + - "null" + type: + enum: + - LAMBDAS + type: string + url: + type: string + userId: + type: string + withCache: + type: boolean + required: + - createdAt + - createdIn + - creator + - deploymentHostname + - name + - id + - plan + - private + - readyState + - type + - url + - userId + type: object + type: array + link: + oneOf: + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + org: + type: string + productionBranch: + type: string + repo: + type: string + repoId: + type: number + sourceless: + type: boolean + type: + enum: + - github + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + productionBranch: + type: string + projectId: + type: string + projectName: + type: string + projectNameWithNamespace: + type: string + projectNamespace: + type: string + projectUrl: + type: string + sourceless: + type: boolean + type: + enum: + - gitlab + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + name: + type: string + owner: + type: string + productionBranch: + type: string + slug: + type: string + sourceless: + type: boolean + type: + enum: + - bitbucket + type: string + updatedAt: + type: number + uuid: + type: string + workspaceUuid: + type: string + required: + - deployHooks + type: object + live: + type: boolean + name: + type: string + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + type: + - string + - "null" + passwordProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + permissions: + properties: + Monitoring: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasGlobal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProject: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsSampling: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsUsage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + auditLog: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingAddress: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInformation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoice: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceEmailRecipient: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceLanguage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPurchaseOrder: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingTaxId: + items: + $ref: "#/components/schemas/ACLAction" + type: array + blob: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifact: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifactUsageEvent: + items: + $ref: "#/components/schemas/ACLAction" + type: array + concurrentBuilds: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connect: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfigurationLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deployment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheck: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckReRunFromProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPrivate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentProductionGit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentRollback: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAcceptDelegation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAuthCodes: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCertificate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCheckConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainRecord: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainTransferIn: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigItem: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigToken: + items: + $ref: "#/components/schemas/ACLAction" + type: array + endpointVerification: + items: + $ref: "#/components/schemas/ACLAction" + type: array + event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + fileUpload: + items: + $ref: "#/components/schemas/ACLAction" + type: array + gitRepository: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationProjects: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationVercelConfigurationOverride: + items: + $ref: "#/components/schemas/ACLAction" + type: array + ipBlocking: + items: + $ref: "#/components/schemas/ACLAction" + type: array + job: + items: + $ref: "#/components/schemas/ACLAction" + type: array + logDrain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringChart: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringQuery: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainExpire: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainMoved: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainRenewal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainUnverified: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationPaymentFailed: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationSpendCap: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationUsageAlert: + items: + $ref: "#/components/schemas/ACLAction" + type: array + openTelemetryEndpoint: + items: + $ref: "#/components/schemas/ACLAction" + type: array + passwordProtection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + paymentMethod: + items: + $ref: "#/components/schemas/ACLAction" + type: array + permissions: + items: + $ref: "#/components/schemas/ACLAction" + type: array + postgres: + items: + $ref: "#/components/schemas/ACLAction" + type: array + previewDeploymentSuffix: + items: + $ref: "#/components/schemas/ACLAction" + type: array + proTrialOnboarding: + items: + $ref: "#/components/schemas/ACLAction" + type: array + project: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDeploymentHook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsUnownedByIntegration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectIntegrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectMember: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + rateLimit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + redis: + items: + $ref: "#/components/schemas/ACLAction" + type: array + remoteCaching: + items: + $ref: "#/components/schemas/ACLAction" + type: array + samlConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + secret: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sensitiveEnvironmentVariablePolicy: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapState: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCaseComment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + team: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamAccessRequest: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamFellowMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInvite: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInviteCode: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamJoin: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembershipDisconnectSAML: + items: + $ref: "#/components/schemas/ACLAction" + type: array + token: + items: + $ref: "#/components/schemas/ACLAction" + type: array + usage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + user: + items: + $ref: "#/components/schemas/ACLAction" + type: array + userConnection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalyticsPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook-event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + type: object + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + publicSource: + type: + - boolean + - "null" + rootDirectory: + type: + - string + - "null" + serverlessFunctionRegion: + type: + - string + - "null" + skipGitConnectDuringLink: + type: boolean + sourceFilesOutsideRootDirectory: + type: boolean + ssoProtection: + properties: + deploymentType: + enum: + - preview + - all + type: string + required: + - deploymentType + type: + - object + - "null" + targets: + additionalProperties: + description: An object containing the deployment's metadata + examples: + - foo: bar + type: string + description: An object containing the deployment's metadata + examples: + - foo: bar + type: object + transferCompletedAt: + type: number + transferStartedAt: + type: number + transferToAccountId: + type: string + transferredFromAccountId: + type: string + updatedAt: + type: number + required: + - accountId + - directoryListing + - id + - name + - nodeVersion + type: object + description: The project information + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The project could not be found + security: + - bearerToken: [] + summary: Find a project by id or name + tags: + - projects + patch: + description: Update the fields of a project using either its `name` or `id`. + operationId: updateProject + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + autoExposeSystemEnvs: + type: boolean + buildCommand: + description: The build command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + commandForIgnoringBuildStep: + maxLength: 256 + type: + - string + - "null" + devCommand: + description: The dev command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + directoryListing: + type: boolean + enablePreviewFeedback: + description: Opt-in to Preview comments on the project level + type: + - boolean + - "null" + framework: + description: The framework that is being used for this project. When `null` is used no framework is selected + enum: + - null + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + description: Specifies whether PRs from Git forks should require a team member's authorization before it can be deployed + type: boolean + gitLFS: + description: Specifies whether Git LFS is enabled for this project. + type: boolean + installCommand: + description: The install command for this project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + name: + description: The desired name for the project + examples: + - a-project-name + maxLength: 100 + pattern: ^[a-z0-9]([a-z0-9]|-[a-z0-9])*$ + type: string + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + description: The output directory of the project. When `null` is used this value will be automatically detected + maxLength: 256 + type: + - string + - "null" + passwordProtection: + additionalProperties: false + description: Allows to protect project deployments with a password + properties: + deploymentType: + description: Specify if the password will apply to every Deployment Target or just Preview + enum: + - all + - preview + type: string + password: + description: The password that will be used to protect Project Deployments + maxLength: 72 + type: + - string + - "null" + required: + - deploymentType + type: + - object + - "null" + publicSource: + description: Specifies whether the source code and logs of the deployments for this project should be public or not + type: + - boolean + - "null" + rootDirectory: + description: The name of a directory or relative path to the source code of your project. When `null` is used it will default to the project root + maxLength: 256 + type: + - string + - "null" + serverlessFunctionRegion: + description: The region to deploy Serverless Functions in this project + maxLength: 4 + type: + - string + - "null" + skipGitConnectDuringLink: + deprecated: true + description: Opts-out of the message prompting a CLI user to connect a Git repository in `vercel link`. + type: boolean + sourceFilesOutsideRootDirectory: + description: Indicates if there are source files outside of the root directory + type: boolean + ssoProtection: + additionalProperties: false + description: Ensures visitors to your Preview Deployments are logged into Vercel and have a minimum of Viewer access on your team + properties: + deploymentType: + default: preview + description: Specify if the Vercel Authentication (SSO Protection) will apply to every Deployment Target or just Preview + enum: + - all + - preview + type: string + required: + - deploymentType + type: + - object + - "null" + type: object + responses: + "200": + content: + application/json: + schema: + properties: + accountId: + type: string + analytics: + properties: + canceledAt: + type: + - number + - "null" + disabledAt: + type: number + enabledAt: + type: number + id: + type: string + paidAt: + type: number + sampleRatePercent: + type: + - number + - "null" + spendLimitInDollars: + type: + - number + - "null" + required: + - id + - canceledAt + - disabledAt + - enabledAt + type: object + autoExposeSystemEnvs: + type: boolean + buildCommand: + type: + - string + - "null" + commandForIgnoringBuildStep: + type: + - string + - "null" + connectBuildsEnabled: + type: boolean + connectConfigurationId: + type: + - string + - "null" + createdAt: + type: number + devCommand: + type: + - string + - "null" + directoryListing: + type: boolean + enablePreviewFeedback: + type: + - boolean + - "null" + env: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + type: array + framework: + enum: + - blitzjs + - nextjs + - gatsby + - remix + - astro + - hexo + - eleventy + - docusaurus-2 + - docusaurus + - preact + - solidstart + - dojo + - ember + - vue + - scully + - ionic-angular + - angular + - polymer + - svelte + - sveltekit + - sveltekit-1 + - ionic-react + - create-react-app + - gridsome + - umijs + - sapper + - saber + - stencil + - nuxtjs + - redwoodjs + - hugo + - jekyll + - brunch + - middleman + - zola + - hydrogen + - vite + - vitepress + - vuepress + - parcel + - sanity + type: + - string + - "null" + gitForkProtection: + type: boolean + gitLFS: + type: boolean + hasActiveBranches: + type: boolean + hasFloatingAliases: + type: boolean + id: + type: string + installCommand: + type: + - string + - "null" + lastRollbackTarget: + properties: + fromDeploymentId: + type: string + jobStatus: + enum: + - succeeded + - failed + - skipped + - pending + - in-progress + type: string + requestedAt: + type: number + toDeploymentId: + type: string + required: + - fromDeploymentId + - toDeploymentId + - jobStatus + - requestedAt + type: + - object + - "null" + latestDeployments: + items: + properties: + alias: + items: + type: string + type: array + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + automaticAliases: + items: + type: string + type: array + buildingAt: + type: number + builds: + items: + properties: + dest: + type: string + src: + type: string + use: + type: string + required: + - use + type: object + type: array + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + type: string + createdAt: + type: number + createdIn: + type: string + creator: + properties: + email: + type: string + githubLogin: + type: string + gitlabLogin: + type: string + uid: + type: string + username: + type: string + required: + - email + - uid + - username + type: + - object + - "null" + deploymentHostname: + type: string + forced: + type: boolean + id: + type: string + meta: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + monorepoManager: + type: + - string + - "null" + name: + type: string + plan: + enum: + - hobby + - enterprise + - pro + - oss + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + private: + type: boolean + readyAt: + type: number + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + type: string + requestedAt: + type: number + target: + type: + - string + - "null" + teamId: + type: + - string + - "null" + type: + enum: + - LAMBDAS + type: string + url: + type: string + userId: + type: string + withCache: + type: boolean + required: + - createdAt + - createdIn + - creator + - deploymentHostname + - name + - id + - plan + - private + - readyState + - type + - url + - userId + type: object + type: array + link: + oneOf: + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + org: + type: string + productionBranch: + type: string + repo: + type: string + repoId: + type: number + sourceless: + type: boolean + type: + enum: + - github + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + productionBranch: + type: string + projectId: + type: string + projectName: + type: string + projectNameWithNamespace: + type: string + projectNamespace: + type: string + projectUrl: + type: string + sourceless: + type: boolean + type: + enum: + - gitlab + type: string + updatedAt: + type: number + required: + - deployHooks + type: object + - properties: + createdAt: + type: number + deployHooks: + items: + properties: + createdAt: + type: number + id: + type: string + name: + type: string + ref: + type: string + url: + type: string + required: + - id + - name + - ref + - url + type: object + type: array + gitCredentialId: + type: string + name: + type: string + owner: + type: string + productionBranch: + type: string + slug: + type: string + sourceless: + type: boolean + type: + enum: + - bitbucket + type: string + updatedAt: + type: number + uuid: + type: string + workspaceUuid: + type: string + required: + - deployHooks + type: object + live: + type: boolean + name: + type: string + nodeVersion: + enum: + - 18.x + - 16.x + - 14.x + - 12.x + - 10.x + type: string + outputDirectory: + type: + - string + - "null" + passwordProtection: + properties: + deploymentType: + enum: + - all + - preview + type: string + required: + - deploymentType + type: + - object + - "null" + permissions: + properties: + Monitoring: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasGlobal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProject: + items: + $ref: "#/components/schemas/ACLAction" + type: array + aliasProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsSampling: + items: + $ref: "#/components/schemas/ACLAction" + type: array + analyticsUsage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + auditLog: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingAddress: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInformation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoice: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceEmailRecipient: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingInvoiceLanguage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingPurchaseOrder: + items: + $ref: "#/components/schemas/ACLAction" + type: array + billingTaxId: + items: + $ref: "#/components/schemas/ACLAction" + type: array + blob: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifact: + items: + $ref: "#/components/schemas/ACLAction" + type: array + cacheArtifactUsageEvent: + items: + $ref: "#/components/schemas/ACLAction" + type: array + concurrentBuilds: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connect: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + connectConfigurationLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deployment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheck: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentCheckReRunFromProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPreview: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentPrivate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentProductionGit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + deploymentRollback: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAcceptDelegation: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainAuthCodes: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCertificate: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainCheckConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainRecord: + items: + $ref: "#/components/schemas/ACLAction" + type: array + domainTransferIn: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigItem: + items: + $ref: "#/components/schemas/ACLAction" + type: array + edgeConfigToken: + items: + $ref: "#/components/schemas/ACLAction" + type: array + endpointVerification: + items: + $ref: "#/components/schemas/ACLAction" + type: array + event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + fileUpload: + items: + $ref: "#/components/schemas/ACLAction" + type: array + gitRepository: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationProjects: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationConfigurationTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + integrationVercelConfigurationOverride: + items: + $ref: "#/components/schemas/ACLAction" + type: array + ipBlocking: + items: + $ref: "#/components/schemas/ACLAction" + type: array + job: + items: + $ref: "#/components/schemas/ACLAction" + type: array + logDrain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringChart: + items: + $ref: "#/components/schemas/ACLAction" + type: array + monitoringQuery: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainExpire: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainMoved: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainPurchase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainRenewal: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationDomainUnverified: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationPaymentFailed: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationSpendCap: + items: + $ref: "#/components/schemas/ACLAction" + type: array + notificationUsageAlert: + items: + $ref: "#/components/schemas/ACLAction" + type: array + openTelemetryEndpoint: + items: + $ref: "#/components/schemas/ACLAction" + type: array + passwordProtection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + paymentMethod: + items: + $ref: "#/components/schemas/ACLAction" + type: array + permissions: + items: + $ref: "#/components/schemas/ACLAction" + type: array + postgres: + items: + $ref: "#/components/schemas/ACLAction" + type: array + previewDeploymentSuffix: + items: + $ref: "#/components/schemas/ACLAction" + type: array + proTrialOnboarding: + items: + $ref: "#/components/schemas/ACLAction" + type: array + project: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDeploymentHook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomain: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectDomainMove: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectEnvVarsUnownedByIntegration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectIntegrationConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectLink: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectMember: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProductionBranch: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectProtectionBypass: + items: + $ref: "#/components/schemas/ACLAction" + type: array + projectTransfer: + items: + $ref: "#/components/schemas/ACLAction" + type: array + rateLimit: + items: + $ref: "#/components/schemas/ACLAction" + type: array + redis: + items: + $ref: "#/components/schemas/ACLAction" + type: array + remoteCaching: + items: + $ref: "#/components/schemas/ACLAction" + type: array + samlConfig: + items: + $ref: "#/components/schemas/ACLAction" + type: array + secret: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sensitiveEnvironmentVariablePolicy: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVars: + items: + $ref: "#/components/schemas/ACLAction" + type: array + sharedEnvVarsProduction: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapConfiguration: + items: + $ref: "#/components/schemas/ACLAction" + type: array + spendCapState: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCase: + items: + $ref: "#/components/schemas/ACLAction" + type: array + supportCaseComment: + items: + $ref: "#/components/schemas/ACLAction" + type: array + team: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamAccessRequest: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamFellowMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInvite: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamInviteCode: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamJoin: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembership: + items: + $ref: "#/components/schemas/ACLAction" + type: array + teamOwnMembershipDisconnectSAML: + items: + $ref: "#/components/schemas/ACLAction" + type: array + token: + items: + $ref: "#/components/schemas/ACLAction" + type: array + usage: + items: + $ref: "#/components/schemas/ACLAction" + type: array + user: + items: + $ref: "#/components/schemas/ACLAction" + type: array + userConnection: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalytics: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webAnalyticsPlan: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook: + items: + $ref: "#/components/schemas/ACLAction" + type: array + webhook-event: + items: + $ref: "#/components/schemas/ACLAction" + type: array + type: object + protectionBypass: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + publicSource: + type: + - boolean + - "null" + rootDirectory: + type: + - string + - "null" + serverlessFunctionRegion: + type: + - string + - "null" + skipGitConnectDuringLink: + type: boolean + sourceFilesOutsideRootDirectory: + type: boolean + ssoProtection: + properties: + deploymentType: + enum: + - all + - preview + type: string + required: + - deploymentType + type: + - object + - "null" + targets: + additionalProperties: + properties: + alias: + items: + type: string + type: array + aliasAssigned: + oneOf: + - type: number + - type: boolean + type: "null" + aliasError: + properties: + code: + type: string + message: + type: string + required: + - code + - message + type: + - object + - "null" + aliasFinal: + type: + - string + - "null" + automaticAliases: + items: + type: string + type: array + buildingAt: + type: number + builds: + items: + properties: + dest: + type: string + src: + type: string + use: + type: string + required: + - use + type: object + type: array + checksConclusion: + enum: + - succeeded + - failed + - skipped + - canceled + type: string + checksState: + enum: + - registered + - running + - completed + type: string + connectConfigurationId: + type: string + createdAt: + type: number + createdIn: + type: string + creator: + properties: + email: + type: string + githubLogin: + type: string + gitlabLogin: + type: string + uid: + type: string + username: + type: string + required: + - email + - uid + - username + type: + - object + - "null" + deploymentHostname: + type: string + forced: + type: boolean + id: + type: string + meta: + additionalProperties: + type: string + description: Construct a type with a set of properties K of type T + type: object + monorepoManager: + type: + - string + - "null" + name: + type: string + plan: + enum: + - hobby + - enterprise + - pro + - oss + type: string + previewCommentsEnabled: + description: Whether or not preview comments are enabled for the deployment + examples: + - false + type: boolean + private: + type: boolean + readyAt: + type: number + readyState: + enum: + - BUILDING + - ERROR + - INITIALIZING + - QUEUED + - READY + - CANCELED + type: string + requestedAt: + type: number + target: + type: + - string + - "null" + teamId: + type: + - string + - "null" + type: + enum: + - LAMBDAS + type: string + url: + type: string + userId: + type: string + withCache: + type: boolean + required: + - createdAt + - createdIn + - creator + - deploymentHostname + - name + - id + - plan + - private + - readyState + - type + - url + - userId + type: + - object + - "null" + type: object + transferCompletedAt: + type: number + transferStartedAt: + type: number + transferToAccountId: + type: string + transferredFromAccountId: + type: string + updatedAt: + type: number + required: + - accountId + - directoryListing + - id + - name + - nodeVersion + type: object + description: The project was succesfuly updated + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + Owner does not have protection add-on + Advanced Deployment Protection is not available for the user plan + "403": + description: You do not have permission to access this resource. + "404": + description: The project was not found + "409": + description: |- + The provided name for the project is already being used + The project is currently being transferred. + security: + - bearerToken: [] + summary: Update an existing project + tags: + - projects + "/v9/projects/{idOrName}/domains": + get: + description: Retrieve the domains associated with a given project by passing either the project `id` or `name` in the URL. + operationId: getProjectDomains + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + oneOf: + - type: string + - type: integer + - description: Filters only production domains when set to `true`. + in: query + name: production + required: false + schema: + default: "false" + description: Filters only production domains when set to `true`. + enum: + - "true" + - "false" + - description: Filters domains based on specific branch. + in: query + name: gitBranch + required: false + schema: + description: Filters domains based on specific branch. + type: string + - description: Excludes redirect project domains when \"false\". Includes redirect project domains when \"true\" (default). + in: query + name: redirects + required: false + schema: + default: "true" + description: Excludes redirect project domains when \"false\". Includes redirect project domains when \"true\" (default). + enum: + - "true" + - "false" + - description: Filters domains based on their redirect target. + in: query + name: redirect + required: false + schema: + description: Filters domains based on their redirect target. + examples: + - example.com + type: string + - description: Filters domains based on their verification status. + in: query + name: verified + required: false + schema: + description: Filters domains based on their verification status. + enum: + - "true" + - "false" + - description: Maximum number of domains to list from a request (max 100). + in: query + name: limit + required: false + schema: + description: Maximum number of domains to list from a request (max 100). + examples: + - 20 + type: number + - description: Get domains created after this JavaScript timestamp. + in: query + name: since + required: false + schema: + description: Get domains created after this JavaScript timestamp. + examples: + - 1609499532000 + type: number + - description: Get domains created before this JavaScript timestamp. + in: query + name: until + required: false + schema: + description: Get domains created before this JavaScript timestamp. + examples: + - 1612264332000 + type: number + - description: Domains sort order by createdAt + in: query + name: order + required: false + schema: + default: DESC + description: Domains sort order by createdAt + enum: + - ASC + - DESC + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + domains: + items: + properties: + apexName: + type: string + createdAt: + type: number + gitBranch: + type: + - string + - "null" + name: + type: string + projectId: + type: string + redirect: + type: + - string + - "null" + redirectStatusCode: + enum: + - 307 + - 301 + - 302 + - 308 + type: + - number + - "null" + updatedAt: + type: number + verification: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + items: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + properties: + domain: + type: string + reason: + type: string + type: + type: string + value: + type: string + required: + - type + - domain + - value + - reason + type: object + type: array + verified: + description: "`true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed." + type: boolean + required: + - name + - apexName + - projectId + - verified + type: object + type: array + pagination: + $ref: "#/components/schemas/Pagination" + required: + - domains + - pagination + type: object + description: Successful response retrieving a list of domains + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Project not found + security: + - bearerToken: [] + summary: Retrieve project domains by project by id or name + tags: + - projects + "/v9/projects/{idOrName}/domains/{domain}": + delete: + description: Remove a domain from a project by passing the domain name and by specifying the project by either passing the project `id` or `name` in the URL. + operationId: removeProjectDomain + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + type: string + - description: The project domain name + in: path + name: domain + required: true + schema: + description: The project domain name + examples: + - www.example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + type: object + description: The domain was succesfully removed from the project + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Project not found + "409": + description: The project is currently being transferred + security: + - bearerToken: [] + summary: Remove a domain from a project + tags: + - projects + get: + description: Get project domain by project id/name and domain name. + operationId: getProjectDomain + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + type: string + - description: The project domain name + in: path + name: domain + required: true + schema: + description: The project domain name + examples: + - www.example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + apexName: + type: string + createdAt: + type: number + gitBranch: + type: + - string + - "null" + name: + type: string + projectId: + type: string + redirect: + type: + - string + - "null" + redirectStatusCode: + enum: + - 307 + - 301 + - 302 + - 308 + type: + - number + - "null" + updatedAt: + type: number + verification: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + items: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + properties: + domain: + type: string + reason: + type: string + type: + type: string + value: + type: string + required: + - type + - domain + - value + - reason + type: object + type: array + verified: + description: "`true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed." + type: boolean + required: + - name + - apexName + - projectId + - verified + type: object + description: "" + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: Project not found + security: + - bearerToken: [] + summary: Get a project domain + tags: + - projects + patch: + description: Update a project domain's configuration, including the name, git branch and redirect of the domain. + operationId: updateProjectDomain + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + type: string + - description: The project domain name + in: path + name: domain + required: true + schema: + description: The project domain name + examples: + - www.example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + gitBranch: + description: Git branch to link the project domain + examples: + - null + maxLength: 250 + type: + - string + - "null" + redirect: + description: Target destination domain for redirect + examples: + - foobar.com + type: + - string + - "null" + redirectStatusCode: + description: Status code for domain redirect + enum: + - null + - 301 + - 302 + - 307 + - 308 + examples: + - 307 + type: + - integer + - "null" + type: object + responses: + "200": + content: + application/json: + schema: + properties: + apexName: + type: string + createdAt: + type: number + gitBranch: + type: + - string + - "null" + name: + type: string + projectId: + type: string + redirect: + type: + - string + - "null" + redirectStatusCode: + enum: + - 307 + - 301 + - 302 + - 308 + type: + - number + - "null" + updatedAt: + type: number + verification: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + items: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + properties: + domain: + type: string + reason: + type: string + type: + type: string + value: + type: string + required: + - type + - domain + - value + - reason + type: object + type: array + verified: + description: "`true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed." + type: boolean + required: + - name + - apexName + - projectId + - verified + type: object + description: The domain was updated successfuly + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + The domain redirect is not valid + "403": + description: You do not have permission to access this resource. + "404": + description: The project was not found + "409": + description: The project is currently being transferred + security: + - bearerToken: [] + summary: Update a project domain + tags: + - projects + "/v9/projects/{idOrName}/domains/{domain}/verify": + post: + description: Attempts to verify a project domain with `verified = false` by checking the correctness of the project domain's `verification` challenge. + operationId: verifyProjectDomain + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_12HKQaOmR5t5Uy6vdcQsNIiZgHGB + type: string + - description: The domain name you want to verify + in: path + name: domain + required: true + schema: + description: The domain name you want to verify + examples: + - example.com + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + properties: + apexName: + type: string + createdAt: + type: number + gitBranch: + type: + - string + - "null" + name: + type: string + projectId: + type: string + redirect: + type: + - string + - "null" + redirectStatusCode: + enum: + - 307 + - 301 + - 302 + - 308 + type: + - number + - "null" + updatedAt: + type: number + verification: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + items: + description: "A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`." + properties: + domain: + type: string + reason: + type: string + type: + type: string + value: + type: string + required: + - type + - domain + - value + - reason + type: object + type: array + verified: + description: "`true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed." + type: boolean + required: + - name + - apexName + - projectId + - verified + type: object + description: |- + The project domain was verified successfully + Domain is already verified + "400": + description: |- + One of the provided values in the request query is invalid. + There is an existing TXT record on the domain verifying it for another project + The domain does not have a TXT record that attempts to verify the project domain + The TXT record on the domain does not match the expected challenge for the project domain + Project domain is not assigned to project + Project domain does not exist + "403": + description: You do not have permission to access this resource. + security: + - bearerToken: [] + summary: Verify project domain + tags: + - projects + "/v9/projects/{idOrName}/env": + get: + description: Retrieve the environment variables for a given project by passing either the project `id` or `name` in the URL. + operationId: filterProjectEnvs + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_XLKmu1DyR1eY7zq8UgeRKbA7yVLA + type: string + - description: If defined, the git branch of the environment variable to filter the results + in: query + name: gitBranch + required: false + schema: + description: If defined, the git branch of the environment variable to filter the results + examples: + - feature-1 + maxLength: 250 + type: string + - description: If true, the environment variable value will be decrypted + in: query + name: decrypt + required: false + schema: + deprecated: true + description: If true, the environment variable value will be decrypted + enum: + - "true" + - "false" + examples: + - "true" + type: string + - description: The source that is calling the endpoint. + in: query + name: source + required: false + schema: + description: The source that is calling the endpoint. + examples: + - vercel-cli:pull + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + type: object + - properties: + envs: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + type: object + type: array + pagination: + $ref: "#/components/schemas/Pagination" + required: + - envs + - pagination + type: object + - description: The list of environment variables for the given project + properties: + envs: + items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + type: object + type: array + required: + - envs + type: object + description: The list of environment variables for the given project + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: The project could not be found + security: + - bearerToken: [] + summary: Retrieve the environment variables of a project by id or name + tags: + - projects + "/v9/projects/{idOrName}/env/{id}": + delete: + description: Delete a specific environment variable for a given project by passing the environment variable identifier and either passing the project `id` or `name` in the URL. + operationId: removeProjectEnv + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_XLKmu1DyR1eY7zq8UgeRKbA7yVLA + type: string + - description: The unique environment variable identifier + in: path + name: id + required: true + schema: + description: The unique environment variable identifier + examples: + - XMbOEya1gUUO1ir4 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + responses: + "200": + content: + application/json: + schema: + oneOf: + - items: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + type: array + - properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + system: + type: boolean + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + - properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + - preview + - development + type: string + type: + enum: + - secret + - system + - encrypted + - plain + - sensitive + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + description: The environment variable was successfully removed + "400": + description: One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + The environment variable could not be found + The project could not be found + "409": + description: The project is being transfered and removing an environment variable is not possible + security: + - bearerToken: [] + summary: Remove an environment variable + tags: + - projects + patch: + description: Edit a specific environment variable for a given project by passing the environment variable identifier and either passing the project `id` or `name` in the URL. + operationId: editProjectEnv + parameters: + - description: The unique project identifier or the project name + in: path + name: idOrName + required: true + schema: + description: The unique project identifier or the project name + examples: + - prj_XLKmu1DyR1eY7zq8UgeRKbA7yVLA + type: string + - description: The unique environment variable identifier + in: path + name: id + required: true + schema: + description: The unique environment variable identifier + examples: + - XMbOEya1gUUO1ir4 + type: string + - description: The Team identifier or slug to perform the request on behalf of. + in: query + name: teamId + schema: + type: string + requestBody: + content: + application/json: + schema: + additionalProperties: false + properties: + gitBranch: + description: The git branch of the environment variable + examples: + - feature-1 + maxLength: 250 + type: + - string + - "null" + key: + description: The name of the environment variable + examples: + - GITHUB_APP_ID + type: string + target: + description: The target environment of the environment variable + examples: + - - preview + items: + enum: + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Productio + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Previe + - mport("/vercel/path0/utils/env-variable-util/types").EnvTarget.Developmen + type: array + type: + description: The type of environment variable + enum: + - system + - secret + - encrypted + - plain + - sensitive + examples: + - plain + type: string + value: + description: The value of the environment variable + examples: + - bkWIjbnxcvo78 + type: string + type: object + responses: + "200": + content: + application/json: + schema: + properties: + configurationId: + type: + - string + - "null" + createdAt: + type: number + createdBy: + type: + - string + - "null" + decrypted: + description: Whether `value` is decrypted. + type: boolean + edgeConfigId: + type: + - string + - "null" + edgeConfigTokenId: + type: + - string + - "null" + gitBranch: + type: string + id: + type: string + key: + type: string + target: + oneOf: + - items: + enum: + - production + - preview + - development + - preview + - development + type: string + type: array + - enum: + - production + - preview + - development + - preview + - development + type: string + type: + enum: + - system + - encrypted + - plain + - sensitive + - secret + type: string + updatedAt: + type: number + updatedBy: + type: + - string + - "null" + value: + type: string + required: + - type + - key + - value + type: object + description: The environment variable was successfully edited + "400": + description: |- + One of the provided values in the request body is invalid. + One of the provided values in the request query is invalid. + "403": + description: You do not have permission to access this resource. + "404": + description: |- + The environment variable could not be found + The project could not be found + "409": + description: The project is being transfered and removing an environment variable is not possible + security: + - bearerToken: [] + summary: Edit an environment variable + tags: + - projects +components: + schemas: + ACLAction: + description: Enum containing the actions that can be performed against a resource. Group operations are included. + enum: + - create + - delete + - read + - update + - list + - count + type: string + AuthToken: + description: Authentication token metadata. + properties: + activeAt: + description: Timestamp (in milliseconds) of when the token was most recently used. + examples: + - 1632816536002 + type: number + createdAt: + description: Timestamp (in milliseconds) of when the token was created. + examples: + - 1632816536002 + type: number + expiresAt: + description: Timestamp (in milliseconds) of when the token expires. + examples: + - 1632816536002 + type: number + id: + description: The unique identifier of the token. + examples: + - 5d9f2ebd38ddca62e5d51e9c1704c72530bdc8bfdd41e782a6687c48399e8391 + type: string + name: + description: The human-readable name of the token. + type: string + origin: + description: The origin of how the token was created. + examples: + - github + type: string + scopes: + description: The access scopes granted to the token. + items: + oneOf: + - description: The access scopes granted to the token. + properties: + createdAt: + type: number + expiresAt: + type: number + origin: + enum: + - saml + - github + - gitlab + - bitbucket + - email + - manual + type: string + type: + enum: + - user + type: string + required: + - type + - origin + - createdAt + type: object + - description: The access scopes granted to the token. + properties: + createdAt: + type: number + expiresAt: + type: number + origin: + enum: + - saml + - github + - gitlab + - bitbucket + - email + - manual + type: string + teamId: + type: string + type: + enum: + - team + type: string + required: + - type + - teamId + - origin + - createdAt + type: object + type: array + type: + description: The type of the token. + examples: + - oauth2-token + type: string + required: + - id + - name + - type + - activeAt + - createdAt + type: object + AuthUser: + description: Data for the currently authenticated User. + properties: + activeDashboardViews: + description: set of dashboard view preferences (cards or list) per scopeId + items: + description: set of dashboard view preferences (cards or list) per scopeId + properties: + scopeId: + type: string + viewPreference: + enum: + - cards + - list + type: string + required: + - scopeId + - viewPreference + type: object + type: array + avatar: + description: SHA1 hash of the avatar for the User account. Can be used in conjuction with the ... endpoint to retrieve the avatar image. + examples: + - 22cb30c85ff45ac4c72de8981500006b28114aa1 + type: + - string + - "null" + billing: + description: An object containing billing infomation associated with the User account. + properties: + addons: + items: + enum: + - custom-deployment-suffix + - live-support + type: string + type: + - array + - "null" + address: + properties: + city: + type: string + country: + type: string + line1: + type: string + line2: + type: string + postalCode: + type: string + state: + type: string + required: + - line1 + type: + - object + - "null" + cancelation: + type: + - number + - "null" + contract: + properties: + end: + type: number + start: + type: number + required: + - start + - end + type: + - object + - "null" + controls: + properties: + analyticsSampleRateInPercent: + type: + - number + - "null" + analyticsSpendLimitInDollars: + type: + - number + - "null" + type: + - object + - "null" + currency: + enum: + - usd + - eur + type: string + email: + type: + - string + - "null" + invoiceItems: + properties: + analytics: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + analyticsUsage: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + artifacts: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + bandwidth: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + builds: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + concurrentBuilds: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + cronJobInvocation: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + customCerts: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + edgeConfigRead: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + edgeConfigWrite: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + edgeFunctionExecutionUnits: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + edgeMiddlewareInvocations: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + enterprise: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + monitoring: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + monitoringMetric: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + passwordProtection: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + previewDeploymentSuffix: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + pro: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + saml: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + serverlessFunctionExecution: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + sourceImages: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + ssoProtection: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + teamSeats: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + webAnalytics: + description: "Will be used to create an invoice item. The price must be in cents: 2000 for $20." + properties: + createdAt: + type: number + disabledAt: + type: + - number + - "null" + frequency: + properties: + interval: + enum: + - month + type: string + intervalCount: + enum: + - 1 + - 3 + - 2 + - 6 + - 12 + type: number + required: + - interval + - intervalCount + type: object + hidden: + type: boolean + maxQuantity: + type: number + name: + type: string + price: + type: number + quantity: + type: number + tier: + type: number + required: + - price + - quantity + - hidden + type: object + webAnalyticsEvent: + properties: + batch: + type: number + disabledAt: + type: + - number + - "null" + hidden: + type: boolean + name: + type: string + price: + type: number + threshold: + type: number + tier: + type: number + required: + - price + - batch + - threshold + - hidden + type: object + type: + - object + - "null" + invoiceSettings: + properties: + footer: + type: string + type: object + language: + type: + - string + - "null" + name: + type: + - string + - "null" + orbCustomerId: + type: string + overdue: + type: + - boolean + - "null" + period: + properties: + end: + type: number + start: + type: number + required: + - start + - end + type: + - object + - "null" + plan: + enum: + - hobby + - enterprise + - pro + type: string + platform: + enum: + - stripe + - stripeTestMode + type: string + pricingExperiment: + enum: + - august-2022 + type: string + programType: + enum: + - startup + - agency + type: string + purchaseOrder: + type: + - string + - "null" + status: + enum: + - active + - canceled + - trialing + - overdue + - expired + type: string + subscriptions: + items: + properties: + discount: + properties: + coupon: + properties: + amountOff: + type: + - number + - "null" + duration: + enum: + - forever + - repeating + - once + type: string + durationInMonths: + type: + - number + - "null" + id: + type: string + name: + type: + - string + - "null" + percentageOff: + type: + - number + - "null" + required: + - id + - name + - amountOff + - percentageOff + - durationInMonths + - duration + type: object + id: + type: string + required: + - id + - coupon + type: + - object + - "null" + frequency: + properties: + interval: + enum: + - month + - day + - week + - year + type: string + intervalCount: + type: number + required: + - interval + - intervalCount + type: object + id: + type: string + items: + items: + properties: + amount: + type: number + id: + type: string + priceId: + type: string + productId: + type: string + quantity: + type: number + required: + - id + - priceId + - productId + - amount + - quantity + type: object + type: array + period: + properties: + end: + type: number + start: + type: number + required: + - start + - end + type: object + trial: + properties: + end: + type: number + start: + type: number + required: + - start + - end + type: + - object + - "null" + required: + - id + - trial + - period + - frequency + - discount + - items + type: object + type: + - array + - "null" + tax: + properties: + id: + type: string + type: + type: string + required: + - type + - id + type: + - object + - "null" + trial: + properties: + end: + type: number + start: + type: number + required: + - start + - end + type: + - object + - "null" + required: + - period + - plan + type: + - object + - "null" + createdAt: + description: UNIX timestamp (in milliseconds) when the User account was created. + examples: + - 1630748523395 + type: number + dismissedToasts: + description: A record of when, under a certain scopeId, a toast was dismissed + items: + description: A record of when, under a certain scopeId, a toast was dismissed + properties: + dismissals: + items: + properties: + createdAt: + type: number + scopeId: + type: string + required: + - scopeId + - createdAt + type: object + type: array + name: + type: string + required: + - name + - dismissals + type: object + type: array + email: + description: Email address associated with the User account. + examples: + - me@example.com + type: string + favoriteProjects: + description: A list of projects across teams that a user has marked as a favorite. + items: + description: A list of projects across teams that a user has marked as a favorite. + properties: + projectId: + type: string + scopeId: + type: string + scopeSlug: + type: string + required: + - projectId + - scopeId + - scopeSlug + type: object + type: array + hasTrialAvailable: + description: Whether the user has a trial available for a paid plan subscription. + type: boolean + id: + description: The User's unique identifier. + examples: + - AEIIDYVk59zbFF2Sxfyxxmua + type: string + importFlowGitNamespace: + oneOf: + - type: string + - type: number + type: "null" + importFlowGitNamespaceId: + oneOf: + - type: string + - type: number + type: "null" + importFlowGitProvider: + enum: + - github + - gitlab + - bitbucket + type: string + name: + description: Name associated with the User account, or `null` if none has been provided. + examples: + - John Doe + type: + - string + - "null" + preferredScopesAndGitNamespaces: + items: + properties: + gitNamespaceId: + oneOf: + - type: string + - type: number + type: "null" + scopeId: + type: string + required: + - scopeId + - gitNamespaceId + type: object + type: array + remoteCaching: + description: remote caching settings + properties: + enabled: + type: boolean + type: object + resourceConfig: + description: An object containing infomation related to the amount of platform resources may be allocated to the User account. + properties: + awsAccountIds: + items: + type: string + type: array + awsAccountType: + type: string + cfZoneName: + type: string + concurrentBuilds: + type: number + edgeConfigSize: + description: To overwrite the maximum size of an Edge Config per account. Size is in kilobytes, eg 64 leads to 64kB or 64_000 bytes worth of storage + type: number + edgeConfigs: + description: To overwrite the number of Edge Configs an account can create. + type: number + nodeType: + type: string + type: object + softBlock: + description: When the User account has been "soft blocked", this property will contain the date when the restriction was enacted, and the identifier for why. + properties: + blockedAt: + type: number + reason: + enum: + - FAIR_USE_LIMITS_EXCEEDED + - ENTERPRISE_TRIAL_ENDED + - BLOCKED_FOR_PLATFORM_ABUSE + - UNPAID_INVOICE + - SUBSCRIPTION_EXPIRED + - SUBSCRIPTION_CANCELED + type: string + required: + - blockedAt + - reason + type: + - object + - "null" + stagingPrefix: + description: Prefix that will be used in the URL of "Preview" deployments created by the User account. + type: string + username: + description: Unique username associated with the User account. + examples: + - jdoe + type: string + required: + - createdAt + - softBlock + - billing + - resourceConfig + - stagingPrefix + - hasTrialAvailable + - id + - email + - name + - username + - avatar + type: object + AuthUserLimited: + description: A limited form of data for the currently authenticated User, due to the authentication token missing privileges to read the full User data. + properties: + avatar: + description: SHA1 hash of the avatar for the User account. Can be used in conjuction with the ... endpoint to retrieve the avatar image. + examples: + - 22cb30c85ff45ac4c72de8981500006b28114aa1 + type: + - string + - "null" + email: + description: Email address associated with the User account. + examples: + - me@example.com + type: string + id: + description: The User's unique identifier. + examples: + - AEIIDYVk59zbFF2Sxfyxxmua + type: string + limited: + description: Property indicating that this User data contains only limited information, due to the authentication token missing privileges to read the full User data. Re-login with email, GitHub, GitLab or Bitbucket in order to upgrade the authentication token with the necessary privileges. + type: boolean + name: + description: Name associated with the User account, or `null` if none has been provided. + examples: + - John Doe + type: + - string + - "null" + username: + description: Unique username associated with the User account. + examples: + - jdoe + type: string + required: + - limited + - id + - email + - name + - username + - avatar + type: object + EdgeConfigItem: + description: The EdgeConfig. + properties: + createdAt: + type: number + edgeConfigId: + type: string + key: + type: string + updatedAt: + type: number + value: + $ref: "#/components/schemas/EdgeConfigItemValue" + required: + - key + - value + - edgeConfigId + - createdAt + - updatedAt + type: object + EdgeConfigItemValue: + oneOf: + - type: string + - type: number + - type: boolean + - type: object + - items: + $ref: "#/components/schemas/EdgeConfigItemValue" + type: array + type: "null" + EdgeConfigToken: + description: The EdgeConfig. + properties: + createdAt: + type: number + edgeConfigId: + type: string + id: + description: This is not the token itself, but rather an id to identify the token by + type: string + label: + type: string + token: + type: string + required: + - token + - label + - id + - edgeConfigId + - createdAt + type: object + FileTree: + description: A deployment file tree entry + properties: + children: + description: The list of children files of the directory (only valid for the `directory` type) + items: + $ref: "#/components/schemas/FileTree" + type: array + contentType: + description: The content-type of the file (only valid for the `file` type) + examples: + - application/json + type: string + mode: + description: The file "mode" indicating file type and permissions. + type: number + name: + description: The name of the file tree entry + examples: + - my-file.json + type: string + symlink: + description: Not currently used. See `file-list-to-tree.ts`. + type: string + type: + description: String indicating the type of file tree entry. + enum: + - directory + - file + - symlink + - lambda + - middleware + - invalid + examples: + - file + type: string + uid: + description: The unique identifier of the file (only valid for the `file` type) + examples: + - 2d4aad419917f15b1146e9e03ddc9bb31747e4d0 + type: string + required: + - name + - type + - mode + type: object + Pagination: + description: This object contains information related to the pagination of the current request, including the necessary parameters to get the next or previous page of data. + properties: + count: + description: Amount of items in the current page. + examples: + - 20 + type: number + next: + description: Timestamp that must be used to request the next page. + examples: + - 1540095775951 + type: + - number + - "null" + prev: + description: Timestamp that must be used to request the previous page. + examples: + - 1540095775951 + type: + - number + - "null" + required: + - count + - next + - prev + type: object + Team: + description: Data representing a Team. + type: object + TeamLimited: + description: A limited form of data representing a Team, due to the authentication token missing privileges to read the full Team data. + properties: + avatar: + description: The ID of the file used as avatar for this Team. + examples: + - 6eb07268bcfadd309905ffb1579354084c24655c + type: + - string + - "null" + created: + description: Will remain undocumented. Remove in v3 API. + type: string + createdAt: + description: UNIX timestamp (in milliseconds) when the Team was created. + examples: + - 1630748523395 + type: number + id: + description: The Team's unique identifier. + examples: + - team_nllPyCtREAqxxdyFKbbMDlxd + type: string + limited: + description: Property indicating that this Team data contains only limited information, due to the authentication token missing privileges to read the full Team data. Re-login with the Team's configured SAML Single Sign-On provider in order to upgrade the authentication token with the necessary privileges. + type: boolean + membership: + oneOf: + - description: The membership of the authenticated User in relation to the Team. + properties: + accessRequestedAt: + type: number + confirmed: + type: boolean + confirmedAt: + type: number + created: + type: number + createdAt: + type: number + joinedFrom: + properties: + commitId: + type: string + dsyncConnectedAt: + type: number + dsyncUserId: + type: string + gitUserId: + oneOf: + - type: string + - type: number + gitUserLogin: + type: string + idpUserId: + type: string + origin: + enum: + - import + - saml + - mail + - link + - teams + - github + - gitlab + - bitbucket + - dsync + - feedback + - organization-teams + type: string + repoId: + type: string + repoPath: + type: string + ssoConnectedAt: + type: number + ssoUserId: + type: string + required: + - origin + type: object + role: + enum: + - MEMBER + - OWNER + - VIEWER + - DEVELOPER + - BILLING + type: string + teamId: + type: string + uid: + type: string + required: + - confirmed + - confirmedAt + - role + - uid + - createdAt + - created + type: object + - description: The membership of the authenticated User in relation to the Team. + properties: + accessRequestedAt: + type: number + confirmed: + type: boolean + confirmedAt: + type: number + created: + type: number + createdAt: + type: number + joinedFrom: + properties: + commitId: + type: string + dsyncConnectedAt: + type: number + dsyncUserId: + type: string + gitUserId: + oneOf: + - type: string + - type: number + gitUserLogin: + type: string + idpUserId: + type: string + origin: + enum: + - import + - saml + - mail + - link + - teams + - github + - gitlab + - bitbucket + - dsync + - feedback + - organization-teams + type: string + repoId: + type: string + repoPath: + type: string + ssoConnectedAt: + type: number + ssoUserId: + type: string + required: + - origin + type: object + role: + enum: + - MEMBER + - OWNER + - VIEWER + - DEVELOPER + - BILLING + type: string + teamId: + type: string + uid: + type: string + required: + - confirmed + - accessRequestedAt + - role + - uid + - createdAt + - created + type: object + name: + description: Name associated with the Team account, or `null` if none has been provided. + examples: + - My Team + type: + - string + - "null" + saml: + description: When "Single Sign-On (SAML)" is configured, this object contains information that allows the client-side to identify whether or not this Team has SAML enforced. + properties: + connection: + description: From T, pick a set of properties whose keys are in the union K + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - creator + - domain + - id + - name + - recordType + - type + - value + type: object + directory: + description: From T, pick a set of properties whose keys are in the union K + properties: + createdAt: + type: + - number + - "null" + creator: + type: string + domain: + type: string + id: + type: string + name: + type: string + recordType: + enum: + - A + - AAAA + - ALIAS + - CAA + - CNAME + - MX + - SRV + - TXT + - NS + type: string + ttl: + type: number + type: + enum: + - record + - record-sys + type: string + value: + type: string + required: + - creator + - domain + - id + - name + - recordType + - type + - value + type: object + enforced: + description: When `true`, interactions with the Team **must** be done with an authentication token that has been authenticated with the Team's SAML Single Sign-On provider. + type: boolean + required: + - enforced + type: object + slug: + description: The Team's slug, which is unique across the Vercel platform. + examples: + - my-team + type: string + required: + - limited + - id + - slug + - name + - avatar + - membership + - created + - createdAt + type: object + UserEvent: + description: Array of events generated by the User. + properties: + createdAt: + description: Timestamp (in milliseconds) of when the event was generated. + examples: + - 1632859321020 + type: number + entities: + description: A list of "entities" within the event `text`. Useful for enhancing the displayed text with additional styling and links. + items: + description: A list of "entities" within the event `text`. Useful for enhancing the displayed text with additional styling and links. + properties: + end: + description: The index of where the entity ends within the `text` (non-inclusive). + examples: + - 3 + type: number + start: + description: The index of where the entity begins within the `text` (inclusive). + examples: + - 0 + type: number + type: + description: The type of entity. + enum: + - target + - author + - bitbucket_login + - bold + - deployment_host + - dns_record + - git_link + - github_login + - gitlab_login + - hook_name + - integration + - edge-config + - link + - project_name + - scaling_rules + - env_var_name + - system + examples: + - author + type: string + required: + - type + - start + - end + type: object + type: array + id: + description: The unique identifier of the Event. + examples: + - uev_bfmMjiMnXfnPbT97dGdpJbCN + type: string + text: + description: The human-readable text of the Event. + examples: + - You logged in via GitHub + type: string + user: + description: Metadata for the User who generated the event. + properties: + avatar: + type: string + email: + type: string + slug: + type: string + uid: + type: string + username: + type: string + required: + - avatar + - email + - uid + - username + type: object + userId: + description: The unique identifier of the User who generated the event. + examples: + - zTuNVUXEAvvnNN3IaqinkyMw + type: string + required: + - id + - text + - entities + - createdAt + - userId + type: object + securitySchemes: + bearerToken: + description: Default authentication mechanism + scheme: bearer + type: http + oauth2: + flows: + authorizationCode: + authorizationUrl: https://api.vercel.com/oauth/authorize + scopes: {} + tokenUrl: https://api.vercel.com/oauth/access_token + type: oauth2 diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/webscraping.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/webscraping.yaml new file mode 100644 index 000000000..cbfab0214 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/webscraping.yaml @@ -0,0 +1,444 @@ +openapi: 3.1.0 +servers: + - url: https://api.webscraping.ai +info: + contact: + email: support@webscraping.ai + name: WebScraping.AI Support + url: https://webscraping.ai + description: A client for https://webscraping.ai API. It provides a web scraping automation API with Chrome JavaScript rendering, rotating proxies, and built-in HTML parsing. + title: WebScraping.AI + version: 3.0.0 + x-apisguru-categories: + - developer_tools + x-origin: + - format: openapi + url: https://webscraping.ai/openapi.yml + version: "3.1" + x-providerName: webscraping.ai +security: + - api_key: [] +tags: + - description: Get full HTML content of pages with proxies and Chrome JS rendering + name: HTML + - description: Get HTML content of selected page areas (like price, search results, page title, etc.) + name: Selected HTML + - description: Information about your account calls quota + name: Account +paths: + /account: + get: + description: Always returns JSON + operationId: account + responses: + "200": + content: + application/json: + example: + remaining_api_calls: 200000 + remaining_concurrency: 100 + resets_at: 1617073667 + schema: + $ref: "#/components/schemas/Account" + description: Success + "403": + $ref: "#/components/responses/403" + summary: Information about your account calls quota + tags: + - Account + /html: + get: + description: Returns just HTML on success, JSON on error + operationId: getHTML + parameters: + - $ref: "#/components/parameters/url" + - $ref: "#/components/parameters/headers" + - $ref: "#/components/parameters/timeout" + - $ref: "#/components/parameters/js" + - $ref: "#/components/parameters/js_timeout" + - $ref: "#/components/parameters/proxy" + - $ref: "#/components/parameters/country" + - $ref: "#/components/parameters/device" + - $ref: "#/components/parameters/error_on_404" + - $ref: "#/components/parameters/error_on_redirect" + responses: + "200": + content: + text/html: + example: |- + + Example Domain + + + +
+

Example Domain

+ + schema: + type: string + description: Success + "400": + $ref: "#/components/responses/400" + "402": + $ref: "#/components/responses/402" + "403": + $ref: "#/components/responses/403" + "429": + $ref: "#/components/responses/429" + "500": + $ref: "#/components/responses/500" + "502": + $ref: "#/components/responses/502" + "503": + $ref: "#/components/responses/503" + "504": + $ref: "#/components/responses/504" + summary: Page HTML by URL + tags: + - HTML + /selected: + get: + description: Returns just HTML on success, JSON on error + operationId: getSelected + parameters: + - description: CSS selector (null by default, returns whole page HTML) + example: h1 + in: query + name: selector + schema: + type: string + - $ref: "#/components/parameters/url" + - $ref: "#/components/parameters/headers" + - $ref: "#/components/parameters/timeout" + - $ref: "#/components/parameters/js" + - $ref: "#/components/parameters/js_timeout" + - $ref: "#/components/parameters/proxy" + - $ref: "#/components/parameters/country" + - $ref: "#/components/parameters/device" + - $ref: "#/components/parameters/error_on_404" + - $ref: "#/components/parameters/error_on_redirect" + responses: + "200": + content: + text/html: + example: More information... + schema: + type: string + description: Success + "400": + $ref: "#/components/responses/400" + "402": + $ref: "#/components/responses/402" + "403": + $ref: "#/components/responses/403" + "429": + $ref: "#/components/responses/429" + "500": + $ref: "#/components/responses/500" + "502": + $ref: "#/components/responses/502" + "503": + $ref: "#/components/responses/503" + "504": + $ref: "#/components/responses/504" + summary: HTML of a selected page area by URL and CSS selector + tags: + - Selected HTML + /selected-multiple: + get: + description: Always returns JSON + operationId: getSelectedMultiple + parameters: + - description: Multiple CSS selectors (null by default, returns whole page HTML) + example: + - h1 + explode: true + in: query + name: selectors + schema: + items: + type: string + type: array + style: form + - $ref: "#/components/parameters/url" + - $ref: "#/components/parameters/headers" + - $ref: "#/components/parameters/timeout" + - $ref: "#/components/parameters/js" + - $ref: "#/components/parameters/js_timeout" + - $ref: "#/components/parameters/proxy" + - $ref: "#/components/parameters/country" + - $ref: "#/components/parameters/device" + - $ref: "#/components/parameters/error_on_404" + - $ref: "#/components/parameters/error_on_redirect" + responses: + "200": + content: + application/json: + example: + - some link + - Hello + schema: + $ref: "#/components/schemas/SelectedAreas" + description: Success + "400": + $ref: "#/components/responses/400" + "402": + $ref: "#/components/responses/402" + "403": + $ref: "#/components/responses/403" + "429": + $ref: "#/components/responses/429" + "500": + $ref: "#/components/responses/500" + "502": + $ref: "#/components/responses/502" + "503": + $ref: "#/components/responses/503" + "504": + $ref: "#/components/responses/504" + summary: HTML of multiple page areas by URL and CSS selectors + tags: + - Selected HTML +components: + parameters: + country: + description: Country of the proxy to use (US by default). Only available on Startup and Custom plans. + example: us + in: query + name: country + schema: + default: us + enum: + - us + - gb + - de + - it + - fr + - ca + - es + - ru + - jp + - kr + type: string + device: + description: Type of device emulation. + example: desktop + in: query + name: device + schema: + default: desktop + enum: + - desktop + - mobile + - tablet + type: string + error_on_404: + description: Return error on 404 HTTP status on the target page (false by default). + example: false + in: query + name: error_on_404 + schema: + default: false + type: boolean + error_on_redirect: + description: Return error on redirect on the target page (false by default). + example: false + in: query + name: error_on_redirect + schema: + default: false + type: boolean + headers: + description: 'HTTP headers to pass to the target page. Can be specified either via a nested query parameter (...&headers[One]=value1&headers=[Another]=value2) or as a JSON encoded object (...&headers={"One": "value1", "Another": "value2"})' + example: '{"Cookie":"session=some_id"}' + explode: true + in: query + name: headers + schema: + additionalProperties: + type: string + type: object + style: deepObject + js: + description: Execute on-page JavaScript using a headless browser (true by default) + example: true + in: query + name: js + schema: + default: true + type: boolean + js_timeout: + description: Maximum JavaScript rendering time in ms. Increase it in case if you see a loading indicator instead of data on the target page. + example: 2000 + in: query + name: js_timeout + schema: + default: 2000 + maximum: 20000 + minimum: 1 + type: integer + postUrl: + description: URL of the target page + example: https://httpbin.org/post + in: query + name: url + required: true + schema: + type: string + proxy: + description: Type of proxy, use residential proxies if your site restricts traffic from datacenters (datacenter by default). Note that residential proxy requests are more expensive than datacenter, see the pricing page for details. + example: datacenter + in: query + name: proxy + schema: + default: datacenter + enum: + - datacenter + - residential + type: string + timeout: + description: Maximum processing time in ms. Increase it in case of timeout errors (10000 by default, maximum is 30000) + example: 10000 + in: query + name: timeout + schema: + default: 10000 + maximum: 30000 + minimum: 1 + type: integer + url: + description: URL of the target page + example: https://example.com + in: query + name: url + required: true + schema: + type: string + requestBodies: + Body: + content: + application/json: + schema: + additionalProperties: true + type: object + application/x-www-form-urlencoded: + schema: + additionalProperties: true + type: object + application/xml: + schema: + additionalProperties: true + type: object + text/plain: + schema: + type: string + description: Request body to pass to the target page + responses: + "400": + content: + application/json: + example: + message: Invalid CSS selector + schema: + $ref: "#/components/schemas/Error" + description: Parameters validation error + "402": + content: + application/json: + example: + message: Some error + schema: + $ref: "#/components/schemas/Error" + description: Billing issue, probably you've ran out of credits + "403": + content: + application/json: + example: + message: Some error + schema: + $ref: "#/components/schemas/Error" + description: Wrong API key + "429": + content: + application/json: + example: + message: Some error + schema: + $ref: "#/components/schemas/Error" + description: Too many concurrent requests + "500": + content: + application/json: + example: + message: Some error + schema: + $ref: "#/components/schemas/Error" + description: Unexpected error, try again or contact support@webscraping.ai + "502": + content: + application/json: + example: + status_code: 500 + status_message: Some website error + schema: + $ref: "#/components/schemas/PageError" + description: "[DEPRECATED] Non-2xx and non-404 HTTP status code on the target page" + "503": + content: + application/json: + example: + status_code: 500 + status_message: Some website error + schema: + $ref: "#/components/schemas/PageError" + description: Non-2xx and non-404 HTTP status code on the target page + "504": + content: + application/json: + example: + message: Some error + schema: + $ref: "#/components/schemas/Error" + description: Timeout error, try increasing timeout parameter value + schemas: + Account: + properties: + remaining_api_calls: + description: Remaining API calls quota + type: integer + remaining_concurrency: + description: Remaining concurrent requests + type: integer + resets_at: + description: Next billing cycle start time (UNIX timestamp) + type: integer + title: Account limits info + type: object + Error: + properties: + message: + description: Error description + type: string + title: Generic error + type: object + PageError: + properties: + status_code: + description: Response HTTP status code (403, 500, etc) + type: integer + status_message: + description: Response HTTP status message + type: string + title: Non-2xx and non-404 HTTP status code on the target page + type: object + SelectedAreas: + description: Array of elements matched by selectors + items: + type: string + title: HTML for selected page areas + type: array + securitySchemes: + api_key: + in: query + name: api_key + type: apiKey diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/wolframalpha.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/wolframalpha.yaml new file mode 100644 index 000000000..156fcb7f7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/3.1.0_openapis/wolframalpha.yaml @@ -0,0 +1,71 @@ +openapi: 3.1.0 +servers: + - description: Wolfram Server for ChatGPT + url: https://www.wolframalpha.com +info: + title: Wolfram + version: v0.1 + x-apisguru-categories: + - machine_learning + x-logo: + url: https://www.wolframcdn.com/images/icons/Wolfram.png + x-origin: + - format: openapi + url: https://www.wolframalpha.com/.well-known/apispec.json + version: "3.1" + x-providerName: wolframalpha.com +paths: + /api/v1/cloud-plugin: + get: + externalDocs: + url: https://reference.wolfram.com/language/ + operationId: getWolframCloudResults + parameters: + - description: the input expression + in: query + name: input + required: true + schema: + type: string + responses: + "200": + content: + text/plain: {} + description: The result of the Wolfram Language evaluation + "400": + description: The request is missing the 'input' parameter + "403": + description: Unauthorized + "500": + description: Wolfram Cloud was unable to generate a result + "503": + description: Service temporarily unavailable. This may be the result of too many requests. + summary: Evaluate Wolfram Language code + /api/v1/llm-api: + get: + externalDocs: + url: https://products.wolframalpha.com/api + operationId: getWolframAlphaResults + parameters: + - description: the input + in: query + name: input + required: true + schema: + type: string + responses: + "200": + content: + text/plain: {} + description: The result of the Wolfram|Alpha query + "400": + description: The request is missing the 'input' parameter + "403": + description: Unauthorized + "500": + description: Wolfram|Alpha was unable to generate a result + "501": + description: Wolfram|Alpha was unable to generate a result + "503": + description: Service temporarily unavailable. This may be the result of too many requests. + summary: Get Wolfram|Alpha results diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/ably.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/ably.yaml new file mode 100644 index 000000000..c549175f5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/azure.iot.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/azure.iot.yaml new file mode 100644 index 000000000..272d117d0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/beezup.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/beezup.yaml new file mode 100644 index 000000000..ec54758f5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/box.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/box.yaml new file mode 100644 index 000000000..4c8eb9127 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/files.com.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/files.com.yaml new file mode 100644 index 000000000..3ebadedab --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/openweathermap.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/openweathermap.yaml new file mode 100644 index 000000000..523874c7e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/soundcloud.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/soundcloud.yaml new file mode 100644 index 000000000..73152229e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/stripe.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/stripe.yaml new file mode 100644 index 000000000..35f1c93aa --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/vimeo.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/vimeo.yaml new file mode 100644 index 000000000..f1f1939ff --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/ynab.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/ynab.yaml new file mode 100644 index 000000000..4ed0ab178 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/zoom.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/ballerinax_connector_tests/zoom.yaml new file mode 100644 index 000000000..0406ad3c1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/client/diagnostic_files/complex_oneOf_schema.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/complex_oneOf_schema.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/complex_oneOf_schema.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/complex_oneOf_schema.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/duplicated_response.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/duplicated_response.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/duplicated_response.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/duplicated_response.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/head_operation.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/head_operation.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/head_operation.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/head_operation.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/header_parameter.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/header_parameter.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/header_parameter.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/header_parameter.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/json_payload.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/json_payload.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/json_payload.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/json_payload.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/openapi_display_annotation.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/openapi_display_annotation.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/openapi_display_annotation.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/openapi_display_annotation.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/operation_delete.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/operation_delete.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/operation_delete.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/operation_delete.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_get.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/petstore_get.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_get.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/petstore_get.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_post.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/petstore_post.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_post.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/petstore_post.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_server_with_base_path.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/petstore_server_with_base_path.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_server_with_base_path.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/petstore_server_with_base_path.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_server_without_base_path.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/petstore_server_without_base_path.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_server_without_base_path.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/petstore_server_without_base_path.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_with_oneOf_response.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/petstore_with_oneOf_response.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/petstore_with_oneOf_response.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/petstore_with_oneOf_response.yaml diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/requestBody_reference_has_inline_object_content_type.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/requestBody_reference_has_inline_object_content_type.yaml new file mode 100644 index 000000000..a6a9cd923 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/requestBody_reference_has_inline_object_content_type.yaml @@ -0,0 +1,68 @@ +openapi: 3.0.0 +info: + title: LaunchDarkly REST API + version: 4.0.0 +paths: + /projects: + post: + operationId: operation01 + requestBody: + $ref: '#/components/requestBodies/deleteFeatureFlagApproval' + responses: + '200': + description: Feature flag approval request response + /projects02: + post: + operationId: operation02 + requestBody: + $ref: '#/components/requestBodies/deleteFeatureFlag' + responses: + '200': + description: Feature flag approval request response + +servers: + - url: https://app.launchdarkly.com/api/v2 +components: + requestBodies: + deleteFeatureFlagApproval: + content: + application/json: + schema: #When schema type is an object + type: object + properties: + comment: + description: comment will be included in audit log item for change. + type: string + description: + description: A name that describes the changes you would like to apply to a feature flag configuration + type: string + notifyMemberIds: + description: Id of members to notify. + example: + - memberId + - memberId2 + items: + type: string + type: array + required: + - description + - instructions + - notifyMemberIds + description: Create a new feature flag approval request + deleteFeatureFlag: + content: + application/json: + schema: #When schema has properties without schema type object + properties: + comment: + type: string + date: + type: string + + description: Create a new feature flag approval request + schemas: + deleteFeatureFlagApprovalRequestFeatureflagapprovalrequestconfigbody: + type: object + properties: + name: + type: string diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/request_body_ref.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/request_body_ref.yaml new file mode 100644 index 000000000..8de6c204f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/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/openapi-cli/src/test/resources/generators/client/diagnostic_files/response_nested_array.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/response_nested_array.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/response_nested_array.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/response_nested_array.yaml diff --git a/openapi-cli/src/test/resources/generators/diagnostic_files/vendor_specific_mime_types.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/vendor_specific_mime_types.yaml new file mode 100644 index 000000000..b50ffc525 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/diagnostic_files/vendor_specific_mime_types.yaml @@ -0,0 +1,72 @@ +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 +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + requestBody: + content: + application/vnd.petstore.v3.diff+json: + schema: + $ref: "#/components/schemas/Pet" + responses: + '200': + description: List of existing pets + content: + application/vnd.petstore.v3.diff+json: + schema: + $ref: "#/components/schemas/Pets" + /v0/pets: + post: + summary: Create a pet + operationId: createPetV0 + requestBody: + content: + application/vnd.petstore.v3.diff+xml: + schema: + $ref: "#/components/schemas/Pet" + responses: + '200': + description: List of existing pets + content: + application/vnd.petstore.v3.diff+xml: + schema: + $ref: "#/components/schemas/Pets" +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/openapi-cli/src/test/resources/generators/client/diagnostic_files/xml_payload.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/xml_payload.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/xml_payload.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/xml_payload.yaml diff --git a/openapi-cli/src/test/resources/generators/client/diagnostic_files/xml_payload_with_ref.yaml b/openapi-cli/src/test/resources/generators/diagnostic_files/xml_payload_with_ref.yaml similarity index 100% rename from openapi-cli/src/test/resources/generators/client/diagnostic_files/xml_payload_with_ref.yaml rename to openapi-cli/src/test/resources/generators/diagnostic_files/xml_payload_with_ref.yaml diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_composed_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_composed_schema.bal new file mode 100644 index 000000000..a4a543ac9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_composed_schema.bal @@ -0,0 +1,81 @@ +# 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?...; +|}; + +# 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?; +}; + +# Mock record +public type Pet record { + string? name?; + int? age?; +}; + +# 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?...; +|}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_invalid_format.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_invalid_format.bal new file mode 100644 index 000000000..ea56fff26 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_invalid_format.bal @@ -0,0 +1,3 @@ +public type Mark record {| + decimal...; +|}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_negative.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_negative.bal new file mode 100644 index 000000000..ba4f9ee66 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_negative.bal @@ -0,0 +1,19 @@ +# Additional properties with object with reference fields - this is issue https://github.com/swagger-api/swagger-parser/issues/1856 +public type User01 record {| + string? name?; + int? id?; + User03?...; +|}; + +# Additional properties type Array with constraint. constraint won't support for rest filed in record. +public type User03 record {| + string? name?; + int? id?; + string[]?...; +|}; + +# These Additional properties are complex to map. +public type User04 record { + string? name?; + int? id?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_true.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_true.bal new file mode 100644 index 000000000..bf1bfc7cb --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/additional_properties_true.bal @@ -0,0 +1,110 @@ +# Additional properties with type number +public type User05 record {| + string? name?; + int? id?; + float...; +|}; + +# Additional properties with type number, nullable true +public type User16 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 {}?...; +|}; + +# Mock record +public type User record { + string? name?; + int? age?; +}; + +# 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 `true` enable +public type User01 record { + string? name?; + int? id?; +}; + +# Additional properties with `false` enable +public type User12 record {| + string? name?; + int? id?; +|}; + +# Additional properties with {} +public type User02 record { + string? name?; + int? id?; +}; + +# Free-form object +public type User13 record { +}; + +# Without additional properties +public type User03 record { + string? name?; + int? id?; +}; + +# 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 type string +public type User04 record {| + string? name?; + int? id?; + string?...; +|}; + +# Additional properties with Array +public type User15 record {| + string? name?; + int? id?; + string[]?...; +|}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/array_with_inline_allOf.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/array_with_inline_allOf.bal index 480ad1a0e..9d459506a 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/array_with_inline_allOf.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/array_with_inline_allOf.bal @@ -19,4 +19,4 @@ public type Owner record { public type NameData record { string FirstName?; string LastName?; -}; \ No newline at end of file +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/additional_properties_with_constraint.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/additional_properties_with_constraint.bal new file mode 100644 index 000000000..776fcec46 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/additional_properties_with_constraint.bal @@ -0,0 +1,15 @@ +public type Additional_Primitive record {| + string name?; + int age?; + string...; +|}; + +public type Additional_NestedArray record {| + boolean isArray?; + string[][]...; +|}; + +public type Additional_Array record {| + boolean isArray?; + string[]...; +|}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/allow_zero_values_for_number_constraint.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/allow_zero_values_for_number_constraint.bal new file mode 100644 index 000000000..44923ce50 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/allow_zero_values_for_number_constraint.bal @@ -0,0 +1,15 @@ +import ballerina/constraint; + +public type Address string; + +public type Person record { + string name?; + string[] hobby?; + @constraint:Int {maxValue: 0} + int id; + Address address?; + @constraint:Float {maxValue: 0} + float salary?; + @constraint:Number {minValue: 0} + decimal net?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/constraint_with_nullable.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/constraint_with_nullable.bal new file mode 100644 index 000000000..25f1a6c4b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/constraint_with_nullable.bal @@ -0,0 +1,12 @@ +# At least one entry should be non-null. +public type Scores decimal[]?; + +public type Average float?; + +public type Pet record { + int id; + string name; + decimal[]? tag?; +}; + +public type Name string?; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/exclusive_min_max_3_1.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/exclusive_min_max_3_1.bal new file mode 100644 index 000000000..33229a109 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/exclusive_min_max_3_1.bal @@ -0,0 +1,10 @@ +import ballerina/constraint; + +public type Person record { + @constraint:Number {minValueExclusive: 10} + decimal net?; + @constraint:Int {maxValueExclusive: 100} + int maxDeliveryCount?; + @constraint:Int {minValue: 1, maxValue: 99} + int service_count?; +}; \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/format_type.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/format_type.bal new file mode 100644 index 000000000..2f3fe3675 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/format_type.bal @@ -0,0 +1,41 @@ +import ballerina/constraint; + +public type StringObject record { + string name?; + byte[] byteContent?; + record {byte[] fileContent; string fileName;} binaryContent?; + @constraint:String {pattern: re `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`} + string uuidContent?; + @constraint:String {pattern: re `^[a-zA-Z][a-zA-Z0-9+.-]*:[a-zA-Z0-9+.-]+$`} + string uriContent?; + @constraint:String {pattern: re `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`} + string dateContent?; + @constraint:String {pattern: re `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`} + string passwordContent?; + @constraint:String {pattern: re `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`} + string datetimeContent?; + @constraint:String {pattern: re `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`} + string emailContent?; + @constraint:String {pattern: re `^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])*$`} + string hostnameContent?; + @constraint:String {pattern: re `^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`} + string ipv4Content?; + @constraint:String {pattern: re `^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`} + string ipv6Content?; +}; + +public type NumberObject record { + string name?; + @constraint:Float {minValue: 0.1} + float floatContent?; + @constraint:Number {maxValue: 200} + decimal doubleContent?; +}; + +public type IntegerObject record { + string name?; + @constraint:Int {maxValue: 2147483647} + int:Signed32 int32Content?; + @constraint:Int {minValue: 0} + int int64Content?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidAndValidConstraintFieldWithDtaType.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidAndValidConstraintFieldWithDtaType.bal new file mode 100644 index 000000000..62a753e0b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidAndValidConstraintFieldWithDtaType.bal @@ -0,0 +1,10 @@ +import ballerina/constraint; + +@constraint:String {maxLength: 5} +public type Address string; + +public type Person record { + string name?; + @constraint:Int {maxValue: 5} + int id; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidConstraintFieldWithDtaType.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidConstraintFieldWithDtaType.bal new file mode 100644 index 000000000..8b6a6dfc2 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/invalidConstraintFieldWithDtaType.bal @@ -0,0 +1,6 @@ +public type Address string; + +public type Person record { + string name?; + int id; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/nested_array.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/nested_array.bal new file mode 100644 index 000000000..9073c4226 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/nested_array.bal @@ -0,0 +1,36 @@ +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[]; + +# 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/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/pattern_except_string_type.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/pattern_except_string_type.bal new file mode 100644 index 000000000..b226025c7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/pattern_except_string_type.bal @@ -0,0 +1,11 @@ +import ballerina/constraint; + +public type PersonHobbyItemsInteger int; + +public type Person record { + int name?; + PersonHobbyItemsInteger[] hobby?; + @constraint:Int {maxValue: 5} + int id; + decimal salary?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/record_field_02.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/record_field_02.bal new file mode 100644 index 000000000..5511525fa --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/record_field_02.bal @@ -0,0 +1,39 @@ +import ballerina/constraint; + +@constraint:String {maxLength: 5000} +public type TaxratesItemsString string; + +@constraint:String {maxLength: 5000} +public type TaxratesanyofItemsString string; + +public type TaxratesoneofarrayItemsNull string|int; + +public type TaxratesanyofarrayItemsNull int|string; + +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 {minValueExclusive: 0} + decimal net?; + @constraint:Int {minValue: 1, maxValue: 100} + int maxDeliveryCount?; + # scenario 01 - field with nullable. + 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/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/string_pattern.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/string_pattern.bal new file mode 100644 index 000000000..7cc40b5b0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/constraint/string_pattern.bal @@ -0,0 +1,16 @@ +import ballerina/constraint; + +@constraint:String {pattern: re `[ a-zA-Z0-9/.+!@#$%^&*()+\- ]*`} +public type PersonHobbyItemsString string; + +public type Person record { + @constraint:String {maxLength: 14} + string name?; + PersonHobbyItemsString[] hobby?; + @constraint:Int {maxValue: 5} + int id; + @constraint:String {pattern: re `^[a-zA-Z0-9_]+$`} + string salary?; + string net?; + int count?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_primitive_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_primitive_schema.bal index bfb094532..7df63f931 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_primitive_schema.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_primitive_schema.bal @@ -3,4 +3,8 @@ public type Pet record { 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/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_string_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_string_schema.bal index ef43f68cd..8c2ae3137 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_string_schema.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/default_optional_string_schema.bal @@ -2,5 +2,7 @@ public type Pet record { int id; string name; string tagName = "TagName"; - string 'type?; + string? 'type = "<|endoftext|>"; + string|string[]? prompt = "<|endoftext|>"; + int|string anyOfField = "<|endoftext|>"; }; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/deprecated_schemas.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/deprecated_schemas.bal index d7b4a01ee..8599b0386 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/deprecated_schemas.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/deprecated_schemas.bal @@ -4,7 +4,7 @@ public type Pets Pet[]; @deprecated public type Owner record { string Name?; - string Address?; + "admin"|"contributor"|"member"|"owner" Address?; }; public type Error record { diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/empty_enum.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/empty_enum.bal new file mode 100644 index 000000000..df7aa7bc6 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/empty_enum.bal @@ -0,0 +1,14 @@ +public type MeetingObject record { + # Meeting topic. + string topic?; + # Meeting Type: 1 - Instant meeting. 2 - Scheduled meeting. 3 - Recurring meeting with no fixed time. 8 - Recurring meeting with fixed time. + int 'type?; +}; + +public type MeetingTypes string?; + +# List of meetings +public type MeetingList record { + # List of Meeting objects. + MeetingObject[] meetings?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/invalid_formats.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/invalid_formats.bal new file mode 100644 index 000000000..80eb8ce9b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/invalid_formats.bal @@ -0,0 +1,8 @@ +public type Pet record { + int id?; + string name; + # pet status in the store + string status?; + string addedDate?; + string points = "50"; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/nested_all_of.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/nested_all_of.bal index 92db7e7d4..91129efc2 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/nested_all_of.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/nested_all_of.bal @@ -1,3 +1,31 @@ +# Make this object schema name with simple case because the tool will convert it to camel case. +public type Account record { + # Username of the account + string username?; + string nickname?; + # The status of the account. Currently the only possible value is "active", but more values may be added in the future + string account_status?; + # Display name of the account + string display_name?; + # Website of the account + string website?; + # The created date of the account + string created_on?; + # The UUID of the account + string uuid?; + # Indicates whether two factor authentication is on + boolean has_2fa_enabled?; +}; + +# Nested allOf with reference +public type User record { + *Account; + # Indicates whether the user represents staff + boolean is_staff?; + # The user's Atlassian account ID + string account_id?; +}; + public type Address record { string streetNo?; string houseNo?; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/nested_schema_refs.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/nested_schema_refs.bal index 259725c13..6fc818bcd 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/nested_schema_refs.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/nested_schema_refs.bal @@ -1,7 +1,3 @@ -public type ProjectGidProjectStatusesBody record { - ProjectStatusRequest data?; -}; - public type ProjectStatusBase record { *ProjectStatusCompact; UserCompact author?; @@ -22,6 +18,10 @@ public type UserCompact record { string name?; }; +public type Project_gid_project_statuses_body record { + ProjectStatusRequest data?; +}; + # A generic Asana Resource, containing a globally unique identifier. public type AsanaResource record { # Globally unique identifier of the resource, as a string. diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/null_empty_record.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/null_empty_record.bal new file mode 100644 index 000000000..e82e97c58 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/null_empty_record.bal @@ -0,0 +1,7 @@ +public type Pet record { + int id; + string name; + string tag?; + string 'type?; + record {}? details?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/null_type_3_1.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/null_type_3_1.bal new file mode 100644 index 000000000..3d416e68b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/null_type_3_1.bal @@ -0,0 +1,10 @@ +public type Category record { + string name?; +}; + +public type Pet record { + int id?; + string? name; + # pet status in the store + "available"|"pending"|"sold"? status?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_array_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_array_schema.bal index cf8b8cf64..c6d866fd6 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_array_schema.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_array_schema.bal @@ -1,19 +1,13 @@ import ballerina/constraint; -public type CustomersCustomerBody record { +public type Customers_customer_body record { # The customer's address. - CustomerAddress|string? address?; + Customer_address|string? address?; # 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. int balance?; }; -public type Customer record { - # The customer's address. - CustomerAddress[]?|string address?; - string name?; -}; - -public type CustomerAddress record { +public type Customer_address record { @constraint:String {maxLength: 5000} string city?; @constraint:String {maxLength: 5000} @@ -27,3 +21,9 @@ public type CustomerAddress record { @constraint:String {maxLength: 5000} string state?; }; + +public type Customer record { + # The customer's address. + Customer_address[]|string? address?; + string name?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_schema.bal index 03525b075..a4f722876 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_schema.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_anyof_schema.bal @@ -1,19 +1,13 @@ import ballerina/constraint; -public type CustomersCustomerBody record { +public type Customers_customer_body record { # The customer's address. - CustomerAdresss|string? address?; + Customer_address|string? address?; # 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. int balance?; }; -public type Customer record { - # The customer's address. - CustomerAdresss? address?; - string name?; -}; - -public type CustomerAdresss record { +public type Customer_address record { @constraint:String {maxLength: 5000} string city?; @constraint:String {maxLength: 5000} @@ -27,3 +21,9 @@ public type CustomerAdresss record { @constraint:String {maxLength: 5000} string state?; }; + +public type Customer record { + # The customer's address. + Customer_address? address?; + string name?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_option_record_schema.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_option_record_schema.bal index cfcfbf52f..8805cfb5c 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_option_record_schema.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/nullable_option_record_schema.bal @@ -1,7 +1,7 @@ - public type ListObject record { - }; +public type ListObject record { +}; - public type UserPlayListDetails record { +public type UserPlayListDetails record { # A link to the Web API endpoint returning the full result of the request string? href?; # The requested data. @@ -15,4 +15,4 @@ # URL to the previous page of items. ( `null` if none) //anydata anydata? previous?; ListObject? total?; - }; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf.bal index 085024428..3aaf8530c 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf.bal @@ -9,7 +9,7 @@ public type Activity record { string uuid?; }; -public type Error Activity|Profile01; +public type Error Activity|Profile01; public type Profile01 record { # First name of the Uber user. diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf_with_inline_schemas.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf_with_inline_schemas.bal index 89fafc646..4d90c3abc 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf_with_inline_schemas.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/oneOf_with_inline_schemas.bal @@ -16,4 +16,4 @@ public type Address record { public type CountryDetails record { string iso_code?; string name?; -}; \ No newline at end of file +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/openapi.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/openapi.bal index d34e05cdd..49a0198da 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/openapi.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/openapi.bal @@ -13,5 +13,6 @@ public type SimpleVaccineTimeline record { # # + fullvaccinetimelinelist - Descriptive Covid-19 vaccine timeline public type FullVaccineTimeline record { - record { decimal total?; decimal daily?; decimal totalPerHundred?; decimal dailyPerMillion?; string date?;} [] fullvaccinetimelinelist; + record {| decimal total?; decimal daily?; decimal totalPerHundred?; decimal dailyPerMillion?; string date?;|} [] + fullvaccinetimelinelist; }; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/recordName.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/recordName.bal index 0a93dc6b9..86ed3ec73 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/recordName.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/recordName.bal @@ -1,4 +1,4 @@ -public type PetDetails record { +public type Pet_details record { int id; string name; string[][][]tag?; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema11.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema11.bal index 834721b77..0bd3c09ed 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/schema11.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema11.bal @@ -1,13 +1,13 @@ +public type Pet_type record { + # type id + string typeId?; + string tagType?; +}; + public type Pet record { int id; # name field string name; string tag?; - PetType 'type?; -}; - -public type PetType record { - # type id - string typeId?; - string tagType?; + Pet_type 'type?; }; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema15.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema15.bal index 01a8e3d29..43d1ebca4 100644 --- a/openapi-cli/src/test/resources/generators/schema/ballerina/schema15.bal +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema15.bal @@ -1,3 +1,11 @@ +import ballerina/constraint; + +@constraint:String {maxLength: 5000} +public type TaxratesItemsString string; + +@constraint:String {maxLength: 5000} +public type SubscriptiondefaulttaxratesItemsString string; + public type Activities record { # Position in pagination. int offset?; @@ -9,11 +17,14 @@ public type User record { string first_name?; # Last name of the Uber user. string last_name?; + TaxratesItemsString[]|"" tax_rates?; }; -public type AnyOF User|Activity; +public type AnyOF User|Activity; public type Activity record { # Unique identifier for the activity string uuid?; }; + +public type Subscription_default_tax_rates SubscriptiondefaulttaxratesItemsString[]|""; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_array.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_array.bal new file mode 100644 index 000000000..558770166 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_array.bal @@ -0,0 +1,25 @@ +import ballerina/constraint; + +@constraint:Int{minValue:1} +public type PetAgeItemsInteger int:Signed32; + +public type Pet_name record { + int:Signed32 id?; + string name?; +}; + +# A pet to be added to the store +public type Pet record { + # Unique identifier for the pet + int:Signed32 id; + # Age of the pet in years + PetAgeItemsInteger[] age; + # Weight of the pet in KG + int:Signed32 weight?; + # Height of the pet in CM + int:Signed32[][]height?; + # Name of the pet + Pet_name[] name; + # Unique identifier of the microchip of the pet + int microchipId?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_invalid_format.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_invalid_format.bal new file mode 100644 index 000000000..098efc0f3 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_invalid_format.bal @@ -0,0 +1,5 @@ +# A pet to be added to the store +public type Pet record { + # Unique identifier for the pet + int id?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32.bal new file mode 100644 index 000000000..ea7873cd3 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32.bal @@ -0,0 +1,19 @@ +import ballerina/constraint; + +# A pet to be added to the store +public type Pet record { + # Unique identifier for the pet + int:Signed32 id; + # Age of the pet in years + @constraint:Int {minValue: 1} + int:Signed32 age; + # Weight of the pet in KG + int:Signed32 weight?; + # Height of the pet in CM + @constraint:Int {maxValue: 10000} + int:Signed32 height?; + # Name of the pet + string name; + # Unique identifier of the microchip of the pet + int microchipId?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32_ref.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32_ref.bal new file mode 100644 index 000000000..ac1fb8435 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed32_ref.bal @@ -0,0 +1,27 @@ +import ballerina/constraint; + +public type Category record { + # Unique identifier for the category + int:Signed32 id?; + # Name of the category + string name?; +}; + +# Unique identifier for the pet +@constraint:Int {minValue: 1} +public type PetId int:Signed32; + +public type Pet record { + # Unique identifier for the pet + PetId id; + # Age of the pet in years + int:Signed32 age; + # Weight of the pet in KG + int:Signed32 weight?; + # Height of the pet in CM + @constraint:Int {maxValue: 10000} + int height?; + # Name of the pet + string name; + Category category?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed64.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed64.bal new file mode 100644 index 000000000..ff92a7ded --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_integer_signed64.bal @@ -0,0 +1,18 @@ +import ballerina/constraint; + +public type Pet record { + # Unique identifier for the pet + int:Signed32 id; + # Name of the pet + string name; + # Unique identifier for the owner + int ownerId; + # Unique identifier of the microchip of the pet + @constraint:Int {minValue: 500} + int microchipId; + # Unique identifier of the insurance policy of the pet + int insurancePolicyId?; + # Gov registration number of the pet + @constraint:Int {minValue: 1000} + int registrationNumber?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_enums.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_enums.bal new file mode 100644 index 000000000..fc41fbad5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_enums.bal @@ -0,0 +1,20 @@ +public type MeetingObject record { + # Meeting topic. + string topic?; + # Meeting Type: 1 - Instant meeting. 2 - Scheduled meeting. 3 - Recurring meeting with no fixed time. 8 - Recurring meeting with fixed time. + 1|2|3|8 'type?; + MeetingTypes broadcastType?; + # Status values that need to be considered for filter + ("available"|"pending")[] status?; + true|false isLive?; + 120.5|300.3 averageAudioLength?; + 300|100? participants?; +}; + +public type MeetingTypes "scheduled"|"live"|"upcoming"; + +# List of meetings +public type MeetingList record { + # List of Meeting objects. + MeetingObject[] meetings?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_nullable_enums.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_nullable_enums.bal new file mode 100644 index 000000000..d9f8f3415 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_nullable_enums.bal @@ -0,0 +1,20 @@ +public type MeetingObject record { + # Meeting topic. + string topic?; + # Meeting Type: 1 - Instant meeting. 2 - Scheduled meeting. 3 - Recurring meeting with no fixed time. 8 - Recurring meeting with fixed time. + 1|2|3|8? 'type?; + MeetingTypes broadcastType?; + # Status values that need to be considered for filter + ("available"|"pending"?)[] status?; + true|false? isLive?; + 120.5|300.3? averageAudioLength?; + 300|100? participants?; +}; + +public type MeetingTypes "scheduled"|"live"|"upcoming"?; + +# List of meetings +public type MeetingList record { + # List of Meeting objects. + MeetingObject[] meetings?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_request_body_ref.bal b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_request_body_ref.bal new file mode 100644 index 000000000..cce2184f5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/ballerina/schema_with_request_body_ref.bal @@ -0,0 +1,23 @@ +public type CreatedPet_RequestBody record { + string petId?; + string createdDate?; +}; + +public type Pets Pet[]; + +public type Error record { + int code; + string message; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_composed_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_composed_schema.yaml new file mode 100644 index 000000000..f8b1918ef --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_composed_schema.yaml @@ -0,0 +1,171 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: "wws" + responses: + "200": + description: successful operation +components: + schemas: + 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_invalid_format.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_invalid_format.yaml new file mode 100644 index 000000000..3e5d0c377 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_invalid_format.yaml @@ -0,0 +1,46 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /marks: + post: + tags: + - pet + summary: Add marks + description: Add marks + operationId: addMarks + requestBody: + description: Add mark + content: + application/json: + schema: + $ref: '#/components/schemas/Mark' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Mark' +components: + schemas: + Mark: + type: object + additionalProperties: + format: double + type: number diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true.yaml new file mode 100644 index 000000000..6f15e1485 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true.yaml @@ -0,0 +1,217 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: "wws" + responses: + "200": + description: successful operation +components: + schemas: + 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 + 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative.yaml new file mode 100644 index 000000000..931b38ab8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative.yaml @@ -0,0 +1,48 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: "wws" + responses: + "200": + description: successful operation +components: + schemas: + User02: + description: Additional properties are with object with reference fields + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative_without_parser_issue.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative_without_parser_issue.yaml new file mode 100644 index 000000000..8d7fcad85 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/additional_properties_true_negative_without_parser_issue.yaml @@ -0,0 +1,75 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: "wws" + responses: + "200": + description: successful operation +components: + schemas: + User01: + description: Additional properties with object with reference fields - this is issue https://github.com/swagger-api/swagger-parser/issues/1856 + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + $ref: "#/components/schemas/User03" + User03: + description: Additional properties type Array with constraint. constraint won't support for rest filed in record. + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: array + maxItems: 9 + items: + type: string + User04: + description: These Additional properties are complex to map. + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + allOf: + - $ref: "#/components/schemas/User03" + - type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/allOf.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/allOf.yaml index 8ab082bc4..870c3a0a2 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/allOf.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/allOf.yaml @@ -43,7 +43,6 @@ components: properties: offset: type: integer - format: int32 description: Position in pagination. history: type: array diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithEmptyObject.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithEmptyObject.yaml index ec65b9a9c..3a276adca 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithEmptyObject.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithEmptyObject.yaml @@ -81,6 +81,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithNoType.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithNoType.yaml index 859b90d16..0c35ac8bb 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithNoType.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/allOfWithNoType.yaml @@ -89,6 +89,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/additional_properties_with_constraint.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/additional_properties_with_constraint.yaml new file mode 100644 index 000000000..12cabb438 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/additional_properties_with_constraint.yaml @@ -0,0 +1,49 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + operationId: "test01" + description: Optional extended description in Markdown. + responses: + '200': + description: OK +components: + schemas: + Additional_Primitive: + properties: + name: + type: string + age: + type: integer + 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 + diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/allow_zero_values_for_number_constraint.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/allow_zero_values_for_number_constraint.yaml new file mode 100644 index 000000000..6668e54d4 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/allow_zero_values_for_number_constraint.yaml @@ -0,0 +1,54 @@ +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: + Address: # Use case 02 : Annotations on a type + type: string + minLength: 0 + Person: + type: object + required: + - id + properties: + name: + type: string + maxLength: 0 # Use case 01 : Annotations on a record field + hobby: + type: array + items: + type: string + maxItems: 0 + minItems: 0 + id: + type: integer + maximum: 0 + 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 + minimum: 0 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/constraint_with_nullable.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/constraint_with_nullable.yaml new file mode 100644 index 000000000..359e3898a --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/constraint_with_nullable.yaml @@ -0,0 +1,79 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /marks: + post: + tags: + - pet + summary: Add marks + description: Add marks + operationId: addMarks + requestBody: + description: Add mark + content: + application/json: + schema: + $ref: '#/components/schemas/Scores' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Scores' +components: + schemas: + Scores: + type: array + items: + type: number + nullable: true + maxItems: 2 + minItems: 2 + nullable: true + description: At least one entry should be non-null. + Name: + type: string + maxLength: 0 + minLength: 10 + nullable: true + Average: + type: number + format: float + minimum: 0.0 + maximum: 12.0 + nullable: true + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: array + items: + type: number + nullable: true + maxItems: 2 + minItems: 2 + nullable: true diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/exclusive_min_max_3_1.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/exclusive_min_max_3_1.yaml new file mode 100644 index 000000000..ba3c16d58 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/exclusive_min_max_3_1.yaml @@ -0,0 +1,42 @@ +openapi: 3.1.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: + - id + properties: + net: + type: number + exclusiveMinimum: 10 + maxDeliveryCount: + type: integer + exclusiveMaximum: 100 + service_count: + type: integer + maximum: 99 + exclusiveMaximum: 100 + minimum: 1 + exclusiveMinimum: 0 \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_0.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_0.yaml new file mode 100644 index 000000000..053dd0f3c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_0.yaml @@ -0,0 +1,112 @@ +openapi: 3.0.0 +info: + title: Format REST API + version: 4.0.0 +paths: + /projects: + get: + operationId: op1 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/StringObject' + post: + operationId: op2 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/IntegerObject' + delete: + operationId: op3 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/NumberObject' +servers: + - url: https://app.launchdarkly.com/api/v2 +components: + schemas: + StringObject: + type: object + properties: + name: + type: string + byteContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: byte + binaryContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: binary + uuidContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: uuid + uriContent: + type: string + format: uri + pattern: ^[a-zA-Z][a-zA-Z0-9+.-]*:[a-zA-Z0-9+.-]+$ + dateContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date + passwordContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: password + datetimeContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date-time + emailContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: email + hostnameContent: + type: string + format: hostname + pattern: ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])*$ + ipv4Content: + type: string + format: ipv4 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + ipv6Content: + type: string + format: ipv6 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + IntegerObject: + type: object + properties: + name: + type: string + int32Content: + type: integer + format: int32 + maximum: 2147483647 + int64Content: + type: integer + format: int64 + minimum: 0 + NumberObject: + type: object + properties: + name: + type: string + floatContent: + type: number + format: float + minimum: 0.1 + doubleContent: + type: number + format: double + maximum: 200 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_1.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_1.yaml new file mode 100644 index 000000000..00808fa5b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/format_types_v3_1.yaml @@ -0,0 +1,112 @@ +openapi: 3.1.0 +info: + title: Format REST API + version: 4.0.0 +paths: + /projects: + get: + operationId: op1 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/StringObject' + post: + operationId: op2 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/IntegerObject' + delete: + operationId: op3 + responses: + '200': + description: Feature flag approval request response + content: + "application/json": + schema: + $ref: '#/components/schemas/NumberObject' +servers: + - url: https://app.launchdarkly.com/api/v2 +components: + schemas: + StringObject: + type: object + properties: + name: + type: string + byteContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: byte + binaryContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: binary + uuidContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: uuid + uriContent: + type: string + format: uri + pattern: ^[a-zA-Z][a-zA-Z0-9+.-]*:[a-zA-Z0-9+.-]+$ + dateContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date + passwordContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: password + datetimeContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: date-time + emailContent: + pattern: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ + type: string + format: email + hostnameContent: + type: string + format: hostname + pattern: ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])*$ + ipv4Content: + type: string + format: ipv4 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + ipv6Content: + type: string + format: ipv6 + pattern: ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ + IntegerObject: + type: object + properties: + name: + type: string + int32Content: + type: integer + format: int32 + maximum: 2147483647 + int64Content: + type: integer + format: int64 + minimum: 0 + NumberObject: + type: object + properties: + name: + type: string + floatContent: + type: number + format: float + minimum: 0.1 + doubleContent: + type: number + format: double + maximum: 200 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidAndValidConstraintFieldWithDataType.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidAndValidConstraintFieldWithDataType.yaml new file mode 100644 index 000000000..d32119cd8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidAndValidConstraintFieldWithDataType.yaml @@ -0,0 +1,35 @@ +openapi: 3.0.0 +info: + title: Shopify Admin API + version: "2021-10" +paths: + /admin: + post: + operationId: "test1" + requestBody: + content: + "application/json": + schema: + $ref: "#/components/schemas/Address" + responses: + 200: + description: Status OK + +components: + schemas: + Address: # 01 : string type has invalid constraint `maximum` and valid constraint `maxLength` + type: string + maximum: 5 + maxLength: 5 + Person: + type: object + required: + - id + properties: + name: + type: string + maximum: 14 # 02 : string type has invalid constraint `maximum` in record field + id: + type: integer + maxItems: 5 # 03 : integer type has invalid constraint `maxItems` + maximum: 5 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidConstraintFieldWithDataType.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidConstraintFieldWithDataType.yaml new file mode 100644 index 000000000..9919fc7b2 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalidConstraintFieldWithDataType.yaml @@ -0,0 +1,39 @@ +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/Address" + responses: + 200: + description: Status OK + +components: + schemas: + Address: # 01 : string type has invalid constraint `maximum` + type: string + maximum: 5 + Person: + type: object + required: + - id + properties: + name: + type: string + maximum: 14 # 02 : string type has invalid constraint `maximum` in record field + id: + type: integer + maxItems: 5 # 03 : integer type has invalid constraint `maxItems` diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalid_pattern_string.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalid_pattern_string.yaml new file mode 100644 index 000000000..562a92a28 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/invalid_pattern_string.yaml @@ -0,0 +1,53 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: string + pattern: [a-zA-Z0-9,\\.\'] + hobby: + type: string + id: + type: integer + maximum: 5 + salary: + type: string + pattern: ^[a-zA-Z0-9_]+$ + net: + type: string + count: + type: integer diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/nested_array_with_constraint.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/nested_array_with_constraint.yaml new file mode 100644 index 000000000..951704e5b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/nested_array_with_constraint.yaml @@ -0,0 +1,94 @@ +openapi: 3.0.1 +info: + title: Main Openapi Yaml + version: 0.1.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /withNestedArray: + get: + operationId: getSayhello + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: "#/components/schemas/NestedArray" + /withConstraint: + get: + operationId: getSay + description: "Nested array without constraint" + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: "#/components/schemas/NestedArray02" + /noConstraint: + get: + operationId: noConstraint + description: "Nested array without constraint" + responses: + "200": + description: Ok + content: + application/json: + schema: + $ref: "#/components/schemas/NoConstraint" +components: + schemas: + 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_except_string_type.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_except_string_type.yaml new file mode 100644 index 000000000..4104de601 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_except_string_type.yaml @@ -0,0 +1,52 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: integer + pattern: '[ a-zA-Z0-9/.+!@#$%^&*()+\- ]*' + hobby: + type: array + items: + type: integer + pattern: '[ a-zA-Z0-9/.+!@#$%^&*()+\- ]*' + id: + type: integer + maximum: 5 + salary: + type: number + pattern: ^[a-zA-Z0-9_]+$ diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_string.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_string.yaml new file mode 100644 index 000000000..cd0e81278 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/pattern_string.yaml @@ -0,0 +1,58 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: string + pattern: ^(?!(.*[\"\*\\\>\<\?\/\:\|]+.*)|(.*[\.]?.*[\.]+$)|(.*[ ]+$)) # Use case 01 : This pattern can not support via Ballerina regex + maxLength: 14 + hobby: + type: array + items: + type: string + pattern: '[ a-zA-Z0-9/.+!@#$%^&*()+\- ]*' + id: + type: integer + maximum: 5 + salary: + type: string + pattern: ^[a-zA-Z0-9_]+$ + net: + type: string + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ # Use case 02 : This pattern can not support via Ballerina regex + count: + type: integer diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/constraint/record_field_02.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/record_field_02.yaml new file mode 100644 index 000000000..72b51f721 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/record_field_02.yaml @@ -0,0 +1,104 @@ +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: + 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 + 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/openapi-cli/src/test/resources/generators/schema/swagger/constraint/union_type.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/constraint/union_type.yaml new file mode 100644 index 000000000..4afa848ec --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/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/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_primitive_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_primitive_schema.yaml index 74280b77c..76d2989a2 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_primitive_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_primitive_schema.yaml @@ -68,3 +68,16 @@ components: 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" diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_string_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_string_schema.yaml index 8c9a866fa..8d93bf990 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_string_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/default_optional_string_schema.yaml @@ -68,3 +68,18 @@ components: default: TagName type: type: string + default: <|endoftext|> + nullable: true + prompt: + default: <|endoftext|> + nullable: true + oneOf: + - type: string + - type: array + items: + type: string + anyOfField: + default: <|endoftext|> + anyOf: + - type: integer + - type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/deprecated_schemas.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/deprecated_schemas.yaml index 8ee1b63aa..b50b4ff01 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/deprecated_schemas.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/deprecated_schemas.yaml @@ -163,6 +163,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/empty_enum.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/empty_enum.yaml new file mode 100644 index 000000000..0f74bd113 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/empty_enum.yaml @@ -0,0 +1,95 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "Employee group" + in: path + name: group + schema: + type: string + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingTypes: + type: string + enum: + - null + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/invalid_formats.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/invalid_formats.yaml new file mode 100644 index 000000000..176ec9851 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/invalid_formats.yaml @@ -0,0 +1,86 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: false + explode: true + schema: + type: string + default: available + enum: + - available + - pending + - sold + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + example: doggie + status: + type: string + description: pet status in the store + addedDate: + type: string + format: date-time + points: + maximum: 50 + minimum: 10 + type: string + format: int32 + default: "50" diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/invalid_pattern_string.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/invalid_pattern_string.yaml new file mode 100644 index 000000000..d43804618 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/invalid_pattern_string.yaml @@ -0,0 +1,43 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: string + pattern: "[a-zA-Z0-9,\\.\']" + hobby: + type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nested_allOf_with_allOf.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nested_allOf_with_allOf.yaml index 91312c0bc..fa3968704 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nested_allOf_with_allOf.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nested_allOf_with_allOf.yaml @@ -68,3 +68,50 @@ components: - properties: zipCode: type: integer + user: + description: "Nested allOf with reference" + allOf: + - $ref: "#/components/schemas/account" + - title: User + type: object + properties: + is_staff: + type: boolean + description: Indicates whether the user represents staff + account_id: + type: string + description: The user's Atlassian account ID + description: A user object + account: + description: "Make this object schema name with simple case because the tool will convert it to camel case." + allOf: + - title: Account + type: object + properties: + username: + type: string + description: Username of the account + nickname: + type: string + account_status: + type: string + description: + The status of the account. Currently the only possible value + is "active", but more values may be added in the future + display_name: + type: string + description: Display name of the account + website: + type: string + description: Website of the account + created_on: + type: string + format: date-time + description: The created date of the account + uuid: + type: string + description: The UUID of the account + has_2fa_enabled: + type: boolean + description: Indicates whether two factor authentication is on + description: An account object. diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/null_empty_record.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/null_empty_record.yaml new file mode 100644 index 000000000..6e5a2474b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/null_empty_record.yaml @@ -0,0 +1,67 @@ +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: 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/Pet" +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + details: + type: object + nullable: true diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/null_type_3_1.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/null_type_3_1.yaml new file mode 100644 index 000000000..b32feeacf --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/null_type_3_1.yaml @@ -0,0 +1,82 @@ +openapi: 3.1.0 +info: + title: Swagger Petstore - OpenAPI 3.1 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.1 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /pet: + post: + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + parameters: + - name: id + schema: + type: + - integer + - "null" + required: true + in: query + - name: name + in: query + schema: + type: + - string + - "null" + default: "doggie" + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + +components: + schemas: + Category: + type: object + properties: + name: + type: + - string + nullable: true + Pet: + required: + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: + - string + - "null" + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + - null \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_anyof_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_anyof_schema.yaml index 78c4a51aa..5945ccfbf 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_anyof_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_anyof_schema.yaml @@ -30,7 +30,7 @@ paths: properties: address: anyOf: - - $ref: "#/components/schemas/customer_adresss" + - $ref: "#/components/schemas/customer_address" - type: string nullable: true description: The customer's address. @@ -50,7 +50,7 @@ paths: description: Successful response. components: schemas: - customer_adresss: + customer_address: properties: city: maxLength: 5000 @@ -76,7 +76,7 @@ components: properties: address: anyOf: - - "$ref": "#/components/schemas/customer_adresss" + - "$ref": "#/components/schemas/customer_address" description: The customer's address. nullable: true name: diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_array_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_array_schema.yaml index d52e1a912..00ac2b9c7 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_array_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_array_schema.yaml @@ -41,7 +41,6 @@ components: limit: description: The maximum number of items in the response (as set in the query or by default). items: - format: int32 type: integer nullable: true next: @@ -49,7 +48,6 @@ components: 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_false.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_false.yaml index 37f1370cd..034135cce 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_false.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_false.yaml @@ -39,7 +39,6 @@ components: $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) @@ -47,7 +46,6 @@ components: 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_array_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_array_schema.yaml index 675569a5f..beabcc457 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_array_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_array_schema.yaml @@ -40,14 +40,12 @@ components: 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_primitive_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_primitive_schema.yaml index d1f989c08..06ee0c609 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_primitive_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_primitive_schema.yaml @@ -39,14 +39,12 @@ components: $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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_record_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_record_schema.yaml index d1f989c08..06ee0c609 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_record_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_option_record_schema.yaml @@ -39,14 +39,12 @@ components: $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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_primitive_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_primitive_schema.yaml index cd88ea1ad..77a6a7b15 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_primitive_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_primitive_schema.yaml @@ -39,7 +39,6 @@ components: $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) @@ -47,7 +46,6 @@ components: 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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_record_schema.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_record_schema.yaml index 14362bf5e..0f3535772 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_record_schema.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_record_schema.yaml @@ -39,14 +39,12 @@ components: $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 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_ref_array.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_ref_array.yaml index 9e366986f..9829fad9c 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/nullable_ref_array.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/nullable_ref_array.yaml @@ -156,6 +156,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/oneOf.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/oneOf.yaml index 7d6d7cc9c..40710ab07 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/oneOf.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/oneOf.yaml @@ -43,7 +43,6 @@ components: properties: offset: type: integer - format: int32 description: Position in pagination. history: type: array diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/referred_inclusion.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/referred_inclusion.yaml index 8869f59bb..4bd76e1be 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/referred_inclusion.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/referred_inclusion.yaml @@ -174,6 +174,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/request_body_with_ref.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/request_body_with_ref.yaml new file mode 100644 index 000000000..725a6a321 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/request_body_with_ref.yaml @@ -0,0 +1,124 @@ +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 + /pets/dogs: + post: + summary: Create a dog pet + operationId: createDogPet + tags: + - pets + requestBody: + description: "Request to add a pet" + $ref: "#/components/requestBodies/CreatedPet" + 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 + message: + type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/scenario02.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/scenario02.yaml index 4830e4ee5..51e962c0e 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/scenario02.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/scenario02.yaml @@ -80,6 +80,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/scenario15.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/scenario15.yaml index be473477a..a48a2efd8 100644 --- a/openapi-cli/src/test/resources/generators/schema/swagger/scenario15.yaml +++ b/openapi-cli/src/test/resources/generators/schema/swagger/scenario15.yaml @@ -11,11 +11,23 @@ paths: summary: Product Types operationId: getProducts description: The Products endpoint returns information about the Uber products - offered at a given location. The response includes the display name and - other details about each product, and lists the products in the proper - display order. + offered at a given location. tags: - Products + parameters: + - in: query + name: subscription_default_tax_rates + required: false + schema: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + style: deepObject responses: "200": description: An array of products @@ -34,6 +46,15 @@ components: last_name: type: string description: Last name of the Uber user. + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string Activity: properties: uuid: @@ -43,7 +64,6 @@ components: properties: offset: type: integer - format: int32 description: Position in pagination. history: type: array diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_array.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_array.yaml new file mode 100644 index 000000000..fda7d4ba8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_array.yaml @@ -0,0 +1,96 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + type: object + description: A pet to be added to the store + required: + - id + - age + - name + properties: + id: + type: integer + format: int32 + example: 10 + description: Unique identifier for the pet + age: + type: array + items: + type: integer + format: int32 + minimum: 1 + description: Age of the pet in years + weight: + type: integer + format: int32 + example: 15 + description: Weight of the pet in KG + height: + type: array + items: + type: array + items: + type: integer + format: int32 + description: Height of the pet in CM + name: + type: array + items: + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + example: doggy + description: Name of the pet + microchipId: + type: integer + format: int64 + example: 123456789012 + description: Unique identifier of the microchip of the pet diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_invalid_format.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_invalid_format.yaml new file mode 100644 index 000000000..b49b5e29c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_invalid_format.yaml @@ -0,0 +1,55 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + type: object + description: A pet to be added to the store + properties: + id: + type: integer + format: invalid_format + example: 10 + description: Unique identifier for the pet diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32.yaml new file mode 100644 index 000000000..695854a80 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32.yaml @@ -0,0 +1,85 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + type: object + description: A pet to be added to the store + required: + - id + - age + - name + properties: + id: + type: integer + format: int32 + example: 10 + description: Unique identifier for the pet + age: + type: integer + format: int32 + example: 12 + description: Age of the pet in years + minimum: 1 + weight: + type: integer + format: int32 + example: 15 + description: Weight of the pet in KG + height: + type: integer + format: int32 + example: 100 + description: Height of the pet in CM + maximum: 10000 + name: + type: string + example: doggy + description: Name of the pet + microchipId: + type: integer + format: int64 + example: 123456789012 + description: Unique identifier of the microchip of the pet diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32_ref.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32_ref.yaml new file mode 100644 index 000000000..721d64a37 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed32_ref.yaml @@ -0,0 +1,115 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + /pets/{petId}: + get: + summary: Info for a specific pet + description: Show a list of pets in the system + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + description: The id of the pet to retrieve + required: true + schema: + $ref: '#/components/schemas/PetId' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + schemas: + PetId: + type: integer + format: int32 + example: 10 + description: Unique identifier for the pet + minimum: 1 + Category: + type: object + properties: + id: + type: integer + format: int32 + example: 1 + description: Unique identifier for the category + name: + type: string + example: dog + description: Name of the category + Pet: + type: object + required: + - id + - age + - name + properties: + id: + $ref: '#/components/schemas/PetId' + age: + type: integer + format: int32 + example: 12 + description: Age of the pet in years + weight: + type: integer + format: int32 + example: 15 + description: Weight of the pet in KG + height: + type: integer + example: 100 + description: Height of the pet in CM + maximum: 10000 + name: + type: string + example: doggy + description: Name of the pet + category: + $ref: '#/components/schemas/Category' diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed64.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed64.yaml new file mode 100644 index 000000000..205393ec7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_integer_signed64.yaml @@ -0,0 +1,85 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + type: object + required: + - id + - name + - ownerId + - microchipId + properties: + id: + type: integer + format: int32 + example: 10 + description: Unique identifier for the pet + name: + type: string + example: doggy + description: Name of the pet + ownerId: + type: integer + format: int64 + example: 123456789012 + description: Unique identifier for the owner + microchipId: + type: integer + format: int64 + example: 123456789012 + description: Unique identifier of the microchip of the pet + minimum: 500 + insurancePolicyId: + type: integer + format: int64 + example: 9876543210 + description: Unique identifier of the insurance policy of the pet + registrationNumber: + type: integer + format: int64 + example: 1648851902 + description: Gov registration number of the pet + minimum: 1000 diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_enums.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_enums.yaml new file mode 100644 index 000000000..dd44839fb --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_enums.yaml @@ -0,0 +1,161 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: + default: live + enum: + - scheduled + - live + - upcoming + type: string + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + default: "available" + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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 + broadcastType: + $ref: '#/components/schemas/MeetingTypes' + status: + description: "Status values that need to be considered for filter" + type: array + items: + type: string + enum: + - "available" + - "pending" + isLive: + type: boolean + enum: + - true + - false + averageAudioLength: + type: number + format: float + enum: + - 120.50 + - 300.30 + participants: + type: integer + nullable: true + enum: + - 300 + - 100 + - null + type: object diff --git a/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_nullable_enums.yaml b/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_nullable_enums.yaml new file mode 100644 index 000000000..96c3248e0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/schema/swagger/schema_with_nullable_enums.yaml @@ -0,0 +1,166 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: + default: live + enum: + - scheduled + - live + - upcoming + type: string + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + default: "available" + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + - null + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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 + - null + type: integer + x-enum-descriptions: + - Instant Meeting + - Scheduled Meeting + - Recurring Meeting with no fixed time + - Recurring Meeting with fixed time + broadcastType: + $ref: '#/components/schemas/MeetingTypes' + status: + description: "Status values that need to be considered for filter" + type: array + items: + type: string + enum: + - "available" + - "pending" + - null + isLive: + type: boolean + enum: + - true + - false + - null + averageAudioLength: + type: number + format: float + enum: + - 120.50 + - 300.30 + - null + participants: + type: integer + nullable: true + enum: + - 300 + - 100 + - null + type: object diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_01.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_01.bal index 9457130d0..e29abea95 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_01.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_01.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get pets(@http:Header string 'x\-request\-id) returns http:Ok { + # Info for a specific pet + # + # + x\-request\-id - parameter description + # + return - An paged array of pets + resource function get pets(@http:Header string x\-request\-id) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_03.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_03.bal new file mode 100644 index 000000000..d5a778f6c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_03.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Info for a specific pet + # + # + x\-request\-id - parameter description + # + return - An paged array of pets + resource function get pets(@http:Header int x\-request\-id) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_05.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_05.bal new file mode 100644 index 000000000..14f9ce119 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_05.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Info for a specific pet + # + # + x\-request\-id - parameter description + # + return - An paged array of pets + resource function get pets(@http:Header int[] x\-request\-id) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_06.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_06.bal index 2cfa4b4f6..18ca49151 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_06.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_06.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string? 'x\-client) returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string? x\-client) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_07.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_07.bal index 34f519889..119ee7f64 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_07.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_07.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string[]? 'x\-client) returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string[]? x\-client) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_08.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_08.bal index 02d73de63..0959762fb 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_08.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_08.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string[]? 'x\-client = ["abc","def"]) returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string[]? x\-client = ["abc","def"]) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_09.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_09.bal index ab582e676..383323474 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_09.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_09.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string 'x\-client = "foo") returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string x\-client = "foo") returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_10.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_10.bal index bbb39fb81..5de5fd886 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_10.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_10.bal @@ -4,6 +4,10 @@ listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); @http:ServiceConfig {treatNilableAsOptional: false} service /v1 on ep0 { - resource function get ping(@http:Header string? 'x\-client) returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string? x\-client) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_11.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_11.bal index 2cfa4b4f6..18ca49151 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_11.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_11.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string? 'x\-client) returns http:Ok { + # Description + # + # + x\-client - parameter description + # + return - Ok + resource function get ping(@http:Header string? x\-client) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_12.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_12.bal index 206cd90a0..7e541aeef 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_12.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_12.bal @@ -3,6 +3,11 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get ping(@http:Header string? 'x\-client, string offest = "abc") returns http:Ok { + # Description + # + # + x\-client - parameter description + # + offest - parameter description + # + return - Ok + resource function get ping(@http:Header string? x\-client, string offest = "abc") returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_invalid.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_invalid.bal new file mode 100644 index 000000000..f40be7c84 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_invalid.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # List all pets + # + # + x\-request\-id - Unique request ID + # + return - An array of pets + resource function get pets(@http:Header int x\-request\-id) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_signed32.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_signed32.bal new file mode 100644 index 000000000..3cc91a21b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_integer_signed32.bal @@ -0,0 +1,15 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # List all pets + # + # + x\-request\-id - Unique request ID + # + x\-registration\-id - Pet's registrationID + # + x\-microchip\-id - Unique microchip ID + # + x\-owner\-id - Pet's owner ID + # + return - An array of pets + resource function get pets(@http:Header int:Signed32 x\-request\-id, @http:Header int:Signed32 x\-registration\-id, @http:Header int:Signed32? x\-microchip\-id, @http:Header int? x\-owner\-id) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_null_required.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_null_required.bal index 03fa13d88..0e263db60 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_null_required.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_null_required.bal @@ -2,7 +2,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); +@http:ServiceConfig {treatNilableAsOptional: false} service /v1 on ep0 { - resource function get pets(@http:Header string x\-request\-id) { + # Info for a specific pet + # + # + 'x\-request\-id - parameter description + # + return - An paged array of pets + resource function get pets(@http:Header string? 'x\-request\-id) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_parameters.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_parameters.bal index 42338a370..a65f8f36e 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_parameters.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_parameters.bal @@ -3,7 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get pets(@http:Header string 'x\-request\-id, - @http:Header string[] 'x\-request\-client) returns http:Ok|http:Response { + # Info for a specific pet + # + # + x\-request\-id - parameter description + # + x\-request\-client - parameter description + # + return - returns can be any of following types + # http:Ok (Expected response to a valid request) + # http:Response (unexpected error) + resource function get pets(@http:Header string x\-request\-id, @http:Header string[] x\-request\-client) returns http:Ok|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_with_reference.bal b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_with_reference.bal new file mode 100644 index 000000000..601bc119a --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/headers/header_with_reference.bal @@ -0,0 +1,20 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Description + # + # + x\-client - parameter description + # + x\-content - parameter description + # + consent\-id - parameter description + # + x\-count - parameter description + # + x\-valid - parameter description + # + x\-sequence - parameter description + # + x\-rate - parameter description + # + x\-modified - parameter description + # + x\-client\-profiles - parameter description + # + return - Ok + resource function get ping(@http:Header XClient x\-client, @http:Header XContent? x\-content, @http:Header string? consent\-id, @http:Header XCount x\-count, @http:Header XValid? x\-valid, @http:Header XSequence? x\-sequence, @http:Header float? x\-rate, @http:Header boolean? x\-modified, @http:Header XClient[]? x\-client\-profiles) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/inline_record.bal b/openapi-cli/src/test/resources/generators/service/ballerina/inline_record.bal index fac1f2645..26c4cd206 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/inline_record.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/inline_record.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post user(@http:Payload UserBody payload) returns InlineResponse200 { + # Creates a new user. + # + # + payload - parameter description + # + return - OK + resource function post user(@http:Payload User_body payload) returns Inline_response_201 { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/intPathParam.bal b/openapi-cli/src/test/resources/generators/service/ballerina/intPathParam.bal new file mode 100644 index 000000000..0cffdfaa1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/intPathParam.bal @@ -0,0 +1,16 @@ +import ballerina/http; + +listener http:Listener ep0 = new(80,config={host:"petstore.openapi.io"}); + +service /v1 on ep0 { + # Info for a specific pet + # + # + storeId - The id of the store to retrieve + # + userId - The id of the user to retrieve + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) + resource function get store/[int storeId]/users/[int userId]/pets/[int:Signed32 petId]() returns Pets|http:Response { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/keywords.bal b/openapi-cli/src/test/resources/generators/service/ballerina/keywords.bal index 1c06de270..fb895f3b3 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/keywords.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/keywords.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (443, config = {host: "petstore.swagger.io"}); service /v2 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - An paged array of pets resource function get pets(int? 'limit) returns Pets { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/importors.bal b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/importors.bal index 534a67549..efbe11b78 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/importors.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/importors.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) resource function get pets(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners.bal b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners.bal index 1eb2ad80d..70ff58a5f 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) resource function get pets(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners03.bal b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners03.bal index 74de125b4..c3f74ed65 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners03.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners03.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) resource function get pets(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners04.bal b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners04.bal index 487707a15..18b94fd1d 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners04.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners04.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (443, config = {host: "api.sendgridf.com"}); service /v3 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - An paged array of pets resource function get pets(int? 'limit) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners05.bal b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners05.bal index f286f78e4..cc1b03537 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners05.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/listeners/listeners05.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (9080, config = {host: "localhost"}); service / on ep0 { - resource function post 'handle\-request(@http:Payload HandlerequestRequestbody payload) returns HandleresponseRequestbody { + # Handle request mediation + # + # + payload - Content of the request + # + return - Successful operation + resource function post handle\-request(@http:Payload HandleRequest_RequestBody payload) returns OkHandleResponse_RequestBody { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/multi_operations.bal b/openapi-cli/src/test/resources/generators/service/ballerina/multi_operations.bal index ba3f689bf..8c2e92425 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/multi_operations.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/multi_operations.bal @@ -3,8 +3,19 @@ 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|http:Response { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { } + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) resource function post pets() returns http:Created|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/multi_paths.bal b/openapi-cli/src/test/resources/generators/service/ballerina/multi_paths.bal index c409ed3ee..0a0866077 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/multi_paths.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/multi_paths.bal @@ -3,18 +3,43 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Info for a specific user + # + # + return - An paged array of pets resource function get .() returns Pets { } + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) resource function get pets(int? 'limit) returns Pets|http:Response { } + # Create a pet + # + # + return - returns can be any of following types + # http:Created (Null response) + # http:Response (unexpected error) resource function post pets() returns http:Created|http:Response { } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) resource function get pets/[string petId]() returns Pets|http:Response { } - resource function get admin/api/'2021\-10/customers/[string customerIdJson](string? fields) returns http:Ok|error { - if !customerIdJson.endsWith(".json") { + # Retrieves a single customer. + # + # + customer_idJson - Customer ID + # + fields - Show only certain fields, specified by a comma-separated list of field names. + # + return - Requested customer + resource function get admin/api/'2021\-10/customers/[string customer_idJson](string? fields) returns http:Ok|error { + if !customer_idJson.endsWith(".json") { return error("bad URL"); } - string customerId = customerIdJson.substring(0, customerIdJson.length() - 4); + string customer_id = customer_idJson.substring(0, customer_idJson.length() - 4); } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/parameter_with_ref_v31.bal b/openapi-cli/src/test/resources/generators/service/ballerina/parameter_with_ref_v31.bal new file mode 100644 index 000000000..7a3dfd2a4 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/parameter_with_ref_v31.bal @@ -0,0 +1,14 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # Add a new pet to the store + # + # + id - parameter description + # + name - parameter description + # + payload - Create a new pet in the store + # + return - Successful operation + resource function post pet(int id, @http:Payload Pet payload, string name = "doggie") returns OkPet { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_enum.bal b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_enum.bal new file mode 100644 index 000000000..6f11f99c0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_enum.bal @@ -0,0 +1,20 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # List meetings + # + # + group - Employee group + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + x\-date\-format - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + x\-time\-zones - Time Zones of attendees + # + location - Meeting location + # + format - The response format you would like + # + return - returns can be any of following types + # MeetingList (HTTP Status Code:200. List of meetings returned.) + # http:NotFound (HTTP Status Code:404 User ID not found. Error Code:1001, User not exist or not belong to this account.) + resource function get users/meetings/["Admin"|"HR"|"Engineering" group](("available"|"pending")[]? status, @http:Header "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? x\-date\-format, @http:Header ("IST"|"GMT"|"UTC")[] x\-time\-zones, "json"|"jsonp"|"msgpack"|"html"? format, "scheduled"|"live"|"upcoming" 'type = "live", RoomNo location = "R5") returns MeetingList|http:NotFound { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_nullable_enums.bal b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_nullable_enums.bal new file mode 100644 index 000000000..3767f255e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_nullable_enums.bal @@ -0,0 +1,18 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # List meetings + # + # + 'type - The meeting types. Scheduled, live or upcoming + # + status - Status values that need to be considered for filter + # + x\-date\-format - Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + # + location - Meeting location + # + format - The response format you would like + # + return - returns can be any of following types + # MeetingList (HTTP Status Code:200. List of meetings returned.) + # http:NotFound (HTTP Status Code:404 User ID not found. Error Code:1001, User not exist or not belong to this account.) + resource function get users/meetings("scheduled"|"live"|"upcoming"? 'type, ("available"|"pending"?)[]? status, @http:Header "UTC"|"LOCAL"|"OFFSET"|"EPOCH"|"LEET"? x\-date\-format, "json"|"jsonp"|"msgpack"|"html"? format, RoomNo location = "R5") returns MeetingList|http:NotFound { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_object_ref_schema.bal b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_object_ref_schema.bal new file mode 100644 index 000000000..ccf57b211 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/parameters_with_object_ref_schema.bal @@ -0,0 +1,19 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # List all the meetings that were scheduled + # + # + organizer - Meeting organizer + # + location - Meeting location + # + types - Meeting Types + # + audience - Meeting audience + # + remarks - Meeting remarks + # + invoices - Booking Invoice + # + return - returns can be any of following types + # MeetingList (HTTP Status Code:200. List of meetings returned.) + # http:NotFound (HTTP Status Code:404 User ID not found. Error Code:1001, User not exist or not belong to this account.) + resource function get users/meetings(Organizer organizer, MeetingTypes[] types, Audience? audience, map remarks, Booking_invoice[] invoices, RoomNo location = "R5") returns MeetingList|http:NotFound { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters.bal b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters.bal index 629abc4f0..17a07f28a 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters.bal @@ -3,7 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + petName - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:Response (unexpected error) resource function get pets/[int petId]/petName/[string petName]() returns Pets|http:Response { } } - diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters02.bal b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters02.bal index 68c3c142b..bc3453af3 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters02.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters02.bal @@ -3,8 +3,23 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get pet(string petId) returns http:Ok {} - resource function get [string petId]/petName/[string petName]() returns Pets {} - resource function get [string petId]() returns Pets {} + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - Expected response to a valid request + resource function get pet(string petId) returns http:Ok { + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + petName - The id of the pet to retrieve + # + return - Expected response to a valid request + resource function get [string petId]/petName/[string petName]() returns Pets { + } + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - Expected response to a valid request + resource function get [string petId]() returns Pets { + } } - diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters03.bal b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters03.bal index 6a8043109..e0f9b737d 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters03.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/path_parameters03.bal @@ -3,6 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service / on ep0 { - resource function get 'storage\-spaces/[string storageSpaceName]/keys/[string 'key]() returns string|http:BadRequest { + # Get key value + # + # + storageSpaceName - name of the storage space + # + 'key - name of the key to retrieve the value + # + return - returns can be any of following types + # string (successful operation) + # http:BadRequest (Invalid key supplied) + resource function get storage\-spaces/[string storageSpaceName]/keys/[string 'key]() returns string|http:BadRequest { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query.bal new file mode 100644 index 000000000..d418a2014 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query.bal @@ -0,0 +1,50 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "virtserver.swaggerhub.com"}); + +service /lnash94/QueryParam/'1\.0\.0 on ep0 { + # searches inventory + # + # + required_query - 1. required query param with inline object + # + optional_query - 2. optional query param with inline object + # + default_query - 3. default query param with inline object + # + reference_query - 4. reference query param + # + required_nullable - 5. required query param with inline object and nullable true + # + optional_nullable - 6. optional query param with inline and nullable object + # + default_nullable - 7. default query param with inline and nullable object + # + reference_nullable - 8. reference_nullable query param won't consider nullable details when it has reference in swagger + # + return - returns can be any of following types + # http:Ok (search results matching criteria) + # http:BadRequest (bad input parameter) + resource function get inventory(Required_query required_query, Optional_query? optional_query, Manufacturer? reference_query, Required_nullable? required_nullable, Optional_nullable? optional_nullable, Manufacturer? reference_nullable, Default_query default_query = {"limit":"9","id":9}, Default_nullable default_nullable = {"limit":"9","id":9}) returns http:Ok|http:BadRequest { + } + # Update inventory + # + # + primitive - 14. object query parameter with additional property with primitive value + # + return - Created + resource function put inventory(record{|PrimitiveValues...;|}? primitive) returns http:Created { + } + # adds an inventory item + # + # + required_query - 9. required query param with inline object including additional properties with reference. + # + optional_query - 10. optional query param with inline object including additional properties integer value. + # + object_nullable - 11. nullable required query param with inline object including additional properties + # + skip_nullable - 12. nullable optional query param with inline object including additional properties + # + add_false - 13. nullable optional query param with inline object including additional properties. + # + payload - Inventory item to add + # + return - item created + resource function post inventory(record{|InventoryItem...;|} required_query, record{|int...;|}? optional_query, record{|InventoryItem...;|}? object_nullable, record{|int...;|}? skip_nullable, Add_false? add_false, @http:Payload InventoryItem payload) returns http:Created { + } + # Update inventory + # + # + arrayRecord - 15. Query parameter with object array + # + return - Created + resource function delete inventory(InventoryItem[]? arrayRecord) returns http:Created { + } + # Update inventory + # + # + additionalArray - 16. Query parameter with record opens with record array + # + return - Created + resource function put inventory02(record{|InventoryItem[]...;|}? additionalArray) returns http:Created { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query_type.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query_type.bal new file mode 100644 index 000000000..121bb19bf --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/object_query_type.bal @@ -0,0 +1,48 @@ +public type InventoryItem record { + string id; + string name; + string releaseDate; + Manufacturer manufacturer; +}; + +public type Default_query record { + string 'limit?; + int id?; +}; + +public type Optional_nullable record { + string rank?; + int id?; +}; + +public type Optional_query record { + string rank?; + int id?; +}; + +public type Manufacturer record { + string name; + string homePage?; + string phone?; +}; + +public type Add_false record {| + string name?; +|}; + +public type Required_nullable record { + string name?; + int id?; +}; + +public type Required_query record { + string name?; + int id?; +}; + +public type Default_nullable record { + string 'limit?; + int id?; +}; + +public type PrimitiveValues 0|1; diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/parameter_with_ref_array_object_schema.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/parameter_with_ref_array_object_schema.bal new file mode 100644 index 000000000..b8b7f5451 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/parameter_with_ref_array_object_schema.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # List all the meetings that were scheduled + # + # + location - Meeting location + # + return - HTTP Status Code:200. List of meetings returned. + resource function get users/meetings(Room[]? location) returns MeetingList { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/parameters_with_object_ref_schema.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/parameters_with_object_ref_schema.bal new file mode 100644 index 000000000..bf76f3f28 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/parameters_with_object_ref_schema.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "petstore3.swagger.io"}); + +service /api/v3 on ep0 { + # List all the meetings that were scheduled + # + # + location - Meeting location + # + return - HTTP Status Code:200. List of meetings returned. + resource function get users/meetings(Room? location) returns MeetingList { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_01.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_01.bal index 877b51c2c..ad857f120 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_01.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_01.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + 'limit - parameter description + # + return - An paged array of pets resource function get pets(int 'limit) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_02.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_02.bal index fde818396..c2f4aec53 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_02.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_02.bal @@ -1,7 +1,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + service /v1 on ep0 { + # Description + # + # + offset - parameter description + # + return - An paged array of pets resource function get pets(int[] offset) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_05.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_05.bal index a4b74131d..61685f8bc 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_05.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_05.bal @@ -1,7 +1,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + service /v1 on ep0 { + # Description + # + # + offset - parameter description + # + return - An paged array of pets resource function get pets(int? offset) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_06.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_06.bal index e0f193620..4dd84a749 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_06.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_06.bal @@ -1,7 +1,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + service /v1 on ep0 { + # Description + # + # + offset - parameter description + # + return - An paged array of pets resource function get pets(int[]? offset) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_09.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_09.bal index 1cad8e2c9..1b95db219 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_09.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_09.bal @@ -3,8 +3,16 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + 'limit - parameter description + # + return - An paged array of pets resource function get pet(int 'limit = 10) returns http:Ok { } + # Description + # + # + petType - parameter description + # + return - An paged array of pets resource function get pets(string[] petType = ["dog","cat"]) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_11.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_11.bal index b6c34c2de..e34cebc2c 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_11.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_11.bal @@ -4,6 +4,10 @@ listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); @http:ServiceConfig {treatNilableAsOptional: false} service /v1 on ep0 { + # Description + # + # + 'limit - parameter description + # + return - An paged array of pets resource function get pet(int? 'limit) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_12.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_12.bal index a864a4b7f..4a6564b10 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_12.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_12.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + petType - parameter description + # + return - An paged array of pets resource function get pets(map? petType) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_13.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_13.bal index fb4dbed2a..c7f1398b5 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_13.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_13.bal @@ -3,8 +3,16 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + petType - parameter description + # + return - An paged array of pets resource function get pets(string petType = "tests") returns http:Ok { } + # Description + # + # + petType - parameter description + # + return - An paged array of pets resource function get pets02(string petType = "tests") returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_14.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_14.bal index bf07603c0..a2a620cf3 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_14.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_14.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + petType01 - parameter description + # + petType02 - parameter description + # + petType03 - parameter description + # + return - An paged array of pets resource function get pets(string? petType02, int petType03, string petType01 = "tests") returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_15.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_15.bal index 8141cb5f1..d8e43b91e 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_15.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_15.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Description + # + # + petType03 - parameter description + # + return - An paged array of pets resource function get pets(int? petType03) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_invalid.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_invalid.bal new file mode 100644 index 000000000..a86974023 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_invalid.bal @@ -0,0 +1,14 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Description + # + # + 'limit - parameter description + # + offset - parameter description + # + next - parameter description + # + return - An paged array of pets + resource function get pets(int 'limit, int? offset, int next) returns int:Signed32 { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_signed32.bal b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_signed32.bal new file mode 100644 index 000000000..16b1a5e9e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/query/query_integer_signed32.bal @@ -0,0 +1,14 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Description + # + # + 'limit - parameter description + # + offset - parameter description + # + next - parameter description + # + return - An paged array of pets + resource function get pets(int:Signed32 'limit, int:Signed32? offset, int next) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/real_apis/box.bal b/openapi-cli/src/test/resources/generators/service/ballerina/real_apis/box.bal index ab48d17d0..ba76ab3d9 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/real_apis/box.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/real_apis/box.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Info for a specific pet + # + # + petId - The id of the pet to retrieve + # + return - returns can be any of following types + # Pets (Expected response to a valid request) + # http:TooManyRequests (unexpected error) resource function get pets/[string petId]() returns Pets|http:TooManyRequests { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_prop_types.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_prop_types.bal new file mode 100644 index 000000000..538f13b72 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_prop_types.bal @@ -0,0 +1,32 @@ +public type Mailing_AddContact_body record { + string name?; +}; + +public type Mailing_AddContact_body_1 record { + string name?; +}; + +public type Mailing_AddContact_body_2 record {| + string name?; + int...; +|}; + +public type MailingViewModel record {| + string? name?; + string? email?; + boolean optPhoneNumber?; + string? phoneNumber?; + string? motivoRecusa?; +|}; + +public type Mailing_AddContact_body_3 record {| + string name?; + MailingViewModel...; +|}; + +public type HistoricoSimulacaoViewModel record {| + string? email?; + string? data?; + string? step?; + string? descricao?; +|}; diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_property.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_property.bal new file mode 100644 index 000000000..fcbc131ac --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/additional_property.bal @@ -0,0 +1,24 @@ +import ballerina/http; + +listener http:Listener ep0 = new (9090, config = {host: "localhost"}); + +service / on ep0 { + # Description + # + # + payload - parameter description + # + return - Success + resource function post api/HistoricoSimulacao/AddHistorico(@http:Payload record {|string...;|}|record {|HistoricoSimulacaoViewModel...;|}|record {|record {|string...;|}...;|} payload) returns http:Ok { + } + # Description + # + # + payload - parameter description + # + return - Success + resource function put api/Mailing/AddContact(@http:Payload Mailing_AddContact_body|Mailing_AddContact_body_1 payload) returns http:Ok { + } + # Description + # + # + payload - parameter description + # + return - Success + resource function post api/Mailing/AddContact(@http:Payload Mailing_AddContact_body_2|Mailing_AddContact_body_3 payload) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/any_of.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/any_of.bal new file mode 100644 index 000000000..54efbd16d --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/any_of.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "api.example.com"}); + +service / on ep0 { + # List all pets + # + # + payload - parameter description + # + return - OK + resource function post pets03(@http:Payload Pets03_body payload) returns http:Created { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/multipart_form_data.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/multipart_form_data.bal new file mode 100644 index 000000000..a2dff6bd0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/multipart_form_data.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (9090, config = {host: "localhost"}); + +service / on ep0 { + # Post operation for the path /user + # + # + request - parameter description + # + return - Successful + resource function post user(http:Request request) returns OkJson { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_requestBody.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_requestBody.bal index 998f957e3..27c40d91f 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_requestBody.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_requestBody.bal @@ -3,14 +3,43 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service / on ep0 { - resource function put storageSpaces01(@http:Payload json payload) returns http:Ok { + # scenario 01: Request body is with oneOf schema for application/json + # + # + payload - parameter description + # + return - Successful operation. + resource function put pet(@http:Payload Pet_body payload) returns http:Ok { } - resource function post storageSpaces01(@http:Payload json payload) returns http:Ok { + # scenario 02: Customised request body with oneOf schema + # + # + payload - Customised request body + # + return - Successful operation. + resource function post pet(@http:Payload Pet_body_1 payload) returns http:Ok { } - resource function put storageSpaces02(@http:Payload string payload) returns http:Ok { + # scenario 04: Request body with oneOf schema with integer, number (primitives) + # + # + payload - Ballerina not support for oneOf data type in request body + # + return - Successful operation. + resource function put pet02(@http:Payload Pet02_body payload) returns http:Ok { } - resource function post storageSpaces02(@http:Payload xml payload) returns http:Ok { + # scenario 03: Request body with oneOf schema with application/xml + # + # + payload - Ballerina not support for oneOf data type in request body + # + return - Successful operation. + resource function post pet02(@http:Payload xml payload) returns http:Ok { } - resource function put storageSpaces/[string name](@http:Payload json payload) returns http:Ok|http:BadRequest { + # scenarios05: requestBody is with oneOf array type + # + # + name - parameter description + # + payload - parameter description + # + return - returns can be any of following types + # http:Ok (Successful operation.) + # http:BadRequest (Invalid storage space name supplied) + resource function put pet/[string name](@http:Payload Pet_name_body payload) returns http:Ok|http:BadRequest { + } + # Description + # + # + request - scenario04: Media type is with not main standard type. + # + return - Successful operation. + resource function post pet04(http:Request request) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_request_body_types.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_request_body_types.bal new file mode 100644 index 000000000..2ef90c43d --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/oneof_request_body_types.bal @@ -0,0 +1,26 @@ +public type Pet02_body string|int|decimal; + +public type Pet_body_1 Dog|Bird; + +public type Pet04_body string|int|decimal; + +public type Bird record { + string name?; + boolean isFly?; +}; + +public type Cat record { + string name?; + string kind?; +}; + +public type Pet02_body_1 Dog|Cat; + +public type Pet_name_body (string|int|decimal)[]; + +public type Pet_body Dog|Cat; + +public type Dog record { + string name?; + string age?; +}; diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/refactor_record_name.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/refactor_record_name.bal index 216bf0b1c..246005ee2 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/refactor_record_name.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/refactor_record_name.bal @@ -3,8 +3,16 @@ import ballerina/http; listener http:Listener ep0 = new (9080, config = {host: "localhost"}); service / on ep0 { - resource function post 'handle\-request(@http:Payload HandlerequestRequestbody payload) returns HandleresponseRequestbody { + # Handle request mediation + # + # + payload - Content of the request + # + return - Successful operation + resource function post handle\-request(@http:Payload HandleRequest_RequestBody payload) returns OkHandleResponse_RequestBody { } - resource function post 'handle\-response(@http:Payload HandlerequestRequestbody payload) returns HandleresponseRequestbody { + # Handle Response + # + # + payload - Content of the request + # + return - Successful operation + resource function post handle\-response(@http:Payload HandleRequest_RequestBody payload) returns OkHandleResponse_RequestBody { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/reference_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/reference_rb.bal index a29ec2e00..f6c2c2bbf 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/reference_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/reference_rb.bal @@ -3,6 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service /pizzashack/'1\.0\.0 on ep0 { - resource function post 'order(@http:Payload Order payload) returns CreatedOrder|BadRequestError|UnsupportedMediaTypeError { + # Create a new Order + # + # + payload - Order object that needs to be added + # + return - returns can be any of following types + # Order (Created. Successful response with the newly created object as entity inthe body.Location header contains URL of newly created entity.) + # BadRequestError (Bad Request. Invalid request or validation error.) + # UnsupportedMediaTypeError (Unsupported Media Type. The entity of the request was in a not supported format.) + resource function post 'order(@http:Payload Order payload) returns Order|BadRequestError|UnsupportedMediaTypeError { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_0102_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_0102_rb.bal index 672222b4b..074f4c7d7 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_0102_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_0102_rb.bal @@ -3,6 +3,16 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + payload - parameter description + # + return - OK resource function post user(@http:Payload byte[] payload) returns http:Ok { } + # Creates a new payment. + # + # + payload - Details of the pet to be purchased + # + return - OK + resource function post payment(@http:Payload byte[] payload) returns http:Ok { + } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_01_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_01_rb.bal index 5853a02df..941662571 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_01_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_01_rb.bal @@ -1,7 +1,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + service /v1 on ep0 { + # Creates a new user. + # + # + payload - parameter description + # + return - OK resource function post user(@http:Payload User payload) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_02_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_02_rb.bal index 2c8d0fc4a..d3ca6a305 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_02_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_02_rb.bal @@ -3,7 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets(@http:Payload{mediaType: ["application/json", "application/xml"]} Pet payload) - returns http:Ok { + # Add a new pet + # + # + payload - Optional description in *Markdown* + # + return - OK + resource function post pets(@http:Payload string|xml|map|Pet payload) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_03_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_03_rb.bal index 5bf3d724b..35405999b 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_03_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_03_rb.bal @@ -3,6 +3,22 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets(@http:Payload Pet payload) returns http:Ok { + # Add a new pet + # + # + request - Optional description in *Markdown* + # + return - OK + resource function put pets(http:Request request) returns http:Ok { } -} + # Add a new pet + # + # + payload - Optional description in *Markdown* + # + return - OK + resource function post pets(@http:Payload string|xml|map|Pet payload) returns http:Ok { + } + # List all pets + # + # + payload - parameter description + # + return - OK + resource function post pets02(@http:Payload xml|Pet payload) returns http:Created { + } +} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_04_rb.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_04_rb.bal index c3076f291..3f1e0b14c 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_04_rb.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/scenario_04_rb.bal @@ -3,6 +3,10 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Add a new pet + # + # + payload - Optional description in *Markdown* + # + return - OK resource function post pets(@http:Payload string payload) returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/unhandled_media_type.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/unhandled_media_type.bal new file mode 100644 index 000000000..82b098ec1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/unhandled_media_type.bal @@ -0,0 +1,25 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "api.example.com"}); + +service / on ep0 { + # Update a user image. + # + # + request - parameter description + # + return - OK + resource function put users(http:Request request) returns http:Ok { + } + # Returns a list of users. + # + # + request - parameter description + # + return - OK + resource function post users(http:Request request) returns http:Ok { + } + # Returns a user by ID. + # + # + id - ID of user to fetch + # + request - parameter description + # + return - OK + resource function put users/[string id](http:Request request) returns http:Ok { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/url_encode.bal b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/url_encode.bal index 987dc0f1e..d62b9bc06 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/url_encode.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/requestBody/url_encode.bal @@ -3,10 +3,22 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service / on ep0 { - resource function post user(@http:Payload {mediaType:"application/x-www-form-urlencoded"} UserBody payload) returns json { + # Post operation for the path /user + # + # + payload - parameter description + # + return - Successful + resource function post user(@http:Payload map payload) returns OkJson { } - resource function post user02(@http:Payload {mediaType:"application/x-www-form-urlencoded"} User payload) returns json { + # Post operation for the path /user + # + # + payload - parameter description + # + return - Successful + resource function post user02(@http:Payload map payload) returns OkJson { } - resource function post user03(@http:Payload {mediaType:"application/x-www-form-urlencoded"} map payload) returns json { + # Post operation for the path /user + # + # + payload - parameter description + # + return - Successful + resource function post user03(@http:Payload map payload) returns OkJson { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/content_null.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/content_null.bal index 5fe841fe8..7c7602019 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/content_null.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/content_null.bal @@ -3,8 +3,14 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - A User object resource function post user() returns http:Accepted { } + # Creates a new user. + # + # + return - A User object resource function post user2() returns http:Accepted { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/different_status_code.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/different_status_code.bal index 91e3f0b70..dbf6fcdde 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/different_status_code.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/different_status_code.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - Email successfully sent resource function post user() returns http:NoContent { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/empty_response.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/empty_response.bal new file mode 100644 index 000000000..19a8e1e17 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/empty_response.bal @@ -0,0 +1,12 @@ +import ballerina/http; + +listener http:Listener ep0 = new (9090, config = {host: "localhost"}); + +service /petstore/v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - http:Response + resource function get pets(int? 'limit) returns http:Response { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/multiline_return_description.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/multiline_return_description.bal new file mode 100644 index 000000000..6fb81513e --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/multiline_return_description.bal @@ -0,0 +1,15 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Show a list of pets in the system. + # Pet can be in any category + # + # + 'limit - How many items to return at one time (max 100). Min is 1 + # + return - returns can be any of following types + # Pets (OK. An paged array of pets) + # http:Response (unexpected error) + resource function get pets(int? 'limit) returns Pets|http:Response { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/path_with_special_characters.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/path_with_special_characters.bal index 4bf82c98f..80f867cf8 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/path_with_special_characters.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/path_with_special_characters.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get 'pets\-path(int? 'limit) returns Pets|http:Response { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get pets\-path(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/petstore_default.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/petstore_default.bal index a64d6beb8..cfe882692 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/petstore_default.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/petstore_default.bal @@ -3,14 +3,40 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service / on ep0 { + # Description + # + # + payload - Created user object + # + return - successful operation resource function post user(@http:Payload User payload) returns http:Response { } + # Description + # + # + username - name that need to be deleted + # + payload - Update an existent user in the store + # + return - successful operation resource function put user/[string username](@http:Payload User payload) returns http:Response { } - resource function get pet/findByStatus(string status = "available") returns http:BadRequest|http:Response { + # Description + # + # + status - Status values that need to be considered for filter + # + return - returns can be any of following types + # http:BadRequest (Invalid status value) + # http:Response (successful operation) + resource function get pet/findByStatus("available"|"pending"|"sold" status = "available") returns http:BadRequest|http:Response { } - resource function post user/createWithList(@http:Payload User[] payload) returns User|http:Response { + # Description + # + # + payload - parameter description + # + return - returns can be any of following types + # OkUser (Successful operation) + # http:Response (successful operation) + resource function post user/createWithList(@http:Payload User[] payload) returns OkUser|http:Response { } + # Logs out current logged in user session + # + # + return - returns can be any of following types + # User (Successful operation) + # http:Response (successful operation) resource function get user/logout() returns User|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/post_method.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/post_method.bal new file mode 100644 index 000000000..35a0b452a --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/post_method.bal @@ -0,0 +1,28 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Creates a new user. + # + # + return - OK + resource function post user() returns http:Ok { + } + # post method with 201 + # + # + return - Created + resource function post user02() returns http:Created { + } + # post method with 201 with content + # + # + return - Created + resource function post user03() returns string { + } + # post method with 201,200 + # + # + return - returns can be any of following types + # string (Created) + # OkString (ok) + resource function post user04() returns string|OkString { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/reference_response.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/reference_response.bal new file mode 100644 index 000000000..146c44c82 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/reference_response.bal @@ -0,0 +1,20 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "api.example.com"}); + +service / on ep0 { + # Gets a list of users. + # + # + return - Unauthorized + resource function get users() returns UnauthorizedError { + } + # Gets a user by ID. + # + # + id - parameter description + # + return - returns can be any of following types + # User (OK) + # UnauthorizedError (Unauthorized) + # NotFoundError (The specified resource was not found) + resource function get users/[int id]() returns User|UnauthorizedError|NotFoundError { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/response_codes.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/response_codes.bal index c94b1f23e..0bac3b09a 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/response_codes.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/response_codes.bal @@ -3,13 +3,67 @@ import ballerina/http; listener http:Listener ep0 = new (9090, config = {host: "localhost"}); service /payloadV on ep0 { - resource function post pet() returns http:Continue|http:SwitchingProtocols|http:Ok|http:Created|http:Accepted| - http:NonAuthoritativeInformation|http:NoContent|http:PartialContent|http:MultipleChoices|http:MovedPermanently| - http:Found|http:SeeOther|http:NotModified|http:UseProxy|http:TemporaryRedirect|http:PermanentRedirect|http:BadRequest| - http:Unauthorized|http:PaymentRequired|http:Forbidden|http:NotFound|http:MethodNotAllowed|http:NotAcceptable| - http:ProxyAuthenticationRequired|http:Conflict|http:Gone|http:LengthRequired|http:PreconditionFailed| - http:PayloadTooLarge|http:UriTooLong|http:UnsupportedMediaType|http:RangeNotSatisfiable|http:ExpectationFailed| - http:UpgradeRequired|http:TooManyRequests|http:RequestHeaderFieldsTooLarge|http:InternalServerError| - http:NotImplemented|http:BadGateway|http:ServiceUnavailable|http:HttpVersionNotSupported { + # Description + # + # + return - returns can be any of following types + # http:Continue (Continue) + # http:SwitchingProtocols (SwitchingProtocols) + # http:Processing (Processing) + # http:EarlyHints (EarlyHints) + # http:Ok (Ok) + # http:Created (Created) + # http:Accepted (Accepted) + # http:NonAuthoritativeInformation (NonAuthoritativeInformation) + # http:NoContent (NoContent) + # http:PartialContent (PartialContent) + # http:MultiStatus (MultiStatus) + # http:AlreadyReported (AlreadyReported) + # http:IMUsed (IMUsed) + # http:MultipleChoices (MultipleChoices) + # http:MovedPermanently (MovedPermanently) + # http:Found (Found) + # http:SeeOther (SeeOther) + # http:NotModified (NotModified) + # http:UseProxy (UseProxy) + # http:TemporaryRedirect (TemporaryRedirect) + # http:PermanentRedirect (PermanentRedirect) + # http:BadRequest (BadRequest) + # http:Unauthorized (Unauthorized) + # http:PaymentRequired (PaymentRequired) + # http:Forbidden (Forbidden) + # http:NotFound (NotFound) + # http:MethodNotAllowed (MethodNotAllowed) + # http:NotAcceptable (NotAcceptable) + # http:ProxyAuthenticationRequired (ProxyAuthenticationRequired) + # http:Conflict (Conflict) + # http:Gone (Gone) + # http:LengthRequired (LengthRequired) + # http:PreconditionFailed (PreconditionFailed) + # http:PayloadTooLarge (PayloadTooLarge) + # http:UriTooLong (UriTooLong) + # http:UnsupportedMediaType (UnsupportedMediaType) + # http:RangeNotSatisfiable (RangeNotSatisfiable) + # http:ExpectationFailed (ExpectationFailed) + # http:MisdirectedRequest (MisDirectedRequest) + # http:UnprocessableEntity (UnProcessableEntity) + # http:Locked (Locked) + # http:FailedDependency (FailedDependency) + # http:TooEarly (TooEarly) + # http:UpgradeRequired (UpgradeRequired) + # http:PreconditionRequired (PredictionRequired) + # http:TooManyRequests (TooManyRequests) + # http:RequestHeaderFieldsTooLarge (RequestHeaderFieldsTooLarge) + # http:UnavailableDueToLegalReasons (UnavailableDueToLegalReasons) + # http:InternalServerError (InternalServerError) + # http:NotImplemented (NotImplemented) + # http:BadGateway (BadGateway) + # http:ServiceUnavailable (ServiceUnavailable) + # http:HttpVersionNotSupported (HttpVersionNotSupported) + # http:VariantAlsoNegotiates (VariantAlsoNegotiates) + # http:InsufficientStorage (InsufficientStorage) + # http:LoopDetected (LoopDetected) + # http:NotExtended (NotExtended) + # http:NetworkAuthenticationRequired (NetworkAuthorizationRequired) + resource function post pet() returns http:Continue|http:SwitchingProtocols|http:Processing|http:EarlyHints|http:Ok|http:Created|http:Accepted|http:NonAuthoritativeInformation|http:NoContent|http:PartialContent|http:MultiStatus|http:AlreadyReported|http:IMUsed|http:MultipleChoices|http:MovedPermanently|http:Found|http:SeeOther|http:NotModified|http:UseProxy|http:TemporaryRedirect|http:PermanentRedirect|http:BadRequest|http:Unauthorized|http:PaymentRequired|http:Forbidden|http:NotFound|http:MethodNotAllowed|http:NotAcceptable|http:ProxyAuthenticationRequired|http:Conflict|http:Gone|http:LengthRequired|http:PreconditionFailed|http:PayloadTooLarge|http:UriTooLong|http:UnsupportedMediaType|http:RangeNotSatisfiable|http:ExpectationFailed|http:MisdirectedRequest|http:UnprocessableEntity|http:Locked|http:FailedDependency|http:TooEarly|http:UpgradeRequired|http:PreconditionRequired|http:TooManyRequests|http:RequestHeaderFieldsTooLarge|http:UnavailableDueToLegalReasons|http:InternalServerError|http:NotImplemented|http:BadGateway|http:ServiceUnavailable|http:HttpVersionNotSupported|http:VariantAlsoNegotiates|http:InsufficientStorage|http:LoopDetected|http:NotExtended|http:NetworkAuthenticationRequired { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/response_has_additional_properties.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/response_has_additional_properties.bal new file mode 100644 index 000000000..c827805f5 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/response_has_additional_properties.bal @@ -0,0 +1,31 @@ +import ballerina/http; + +listener http:Listener ep0 = new (443, config = {host: "api.example.com"}); + +service / on ep0 { + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory() returns Inline_response_200 { + } + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory02() returns StoreInventory02Response|string { + } + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory03() returns StoreInventory03Response { + } + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory04() returns StoreInventory04Response { + } + # Description + # + # + return - successful operation + resource function get store/inventory05() returns BadRequestStoreInventory05Response { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_01_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_01_rs.bal index 088e63ee7..0c6d71646 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_01_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_01_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - OK resource function post user() returns http:Ok { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_02_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_02_rs.bal index f3d48ced3..7983a762d 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_02_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_02_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post user() returns string { + # Creates a new user. + # + # + return - OK + resource function post user() returns OkString { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_03_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_03_rs.bal index b4cdc3203..6af558e82 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_03_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_03_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - OK resource function post user() returns User { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_04_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_04_rs.bal index 63038a108..c3f34fe06 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_04_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_04_rs.bal @@ -3,6 +3,13 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - returns can be any of following types + # http:Ok (OK) + # http:BadRequest (Bad request. User ID must be an integer and larger than 0.) + # http:Unauthorized (Authorization information is missing or invalid.) + # http:NotFound (A user with the specified ID was not found.) resource function post user() returns http:Ok|http:BadRequest|http:Unauthorized|http:NotFound { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_05_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_05_rs.bal index 0208508e5..97b5f4108 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_05_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_05_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - A User object resource function post user() returns BadRequestString { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_06_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_06_rs.bal index 490e432d6..abb0010ad 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_06_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_06_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new user. + # + # + return - A User object resource function post user() returns BadRequestError { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_07_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_07_rs.bal index b9e089ec1..65c6a2104 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_07_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_07_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - A list of pets resource function post pets() returns Pet|xml|string { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_08_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_08_rs.bal index d314cdcee..363b6a577 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_08_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_08_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns InlineResponse200 { + # Creates a new pets. + # + # + return - A User object + resource function post pets() returns Inline_response_201 { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_09_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_09_rs.bal index f2def2b12..8120f5d22 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_09_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_09_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns BadRequestInlineResponse400 { + # Creates a new pets. + # + # + return - A User object + resource function post pets() returns BadRequestInline_response_400 { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_10_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_10_rs.bal index e8110bd96..bb2596ee1 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_10_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_10_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns json { + # Creates a new pets. + # + # + return - A User object + resource function post pets() returns anydata { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_11_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_11_rs.bal index d314cdcee..a21241608 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_11_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_11_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns InlineResponse200 { + # Creates a new pets. + # + # + return - A JSON object containing pet information + resource function post pets() returns Inline_response_201 { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_12_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_12_rs.bal index f2def2b12..44d47ab9e 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_12_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_12_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns BadRequestInlineResponse400 { + # Creates a new pets. + # + # + return - A JSON object containing pet information + resource function post pets() returns BadRequestInline_response_400 { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_13_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_13_rs.bal index bf49f71d8..336e4d2b8 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_13_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_13_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - A list of users resource function post pets() returns BadRequestUserXmlString { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_14_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_14_rs.bal index 70a0196da..f08671cbd 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_14_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_14_rs.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function post pets() returns User|BadRequestError|NotFoundError { + # Creates a new pets. + # + # + return - returns can be any of following types + # OkUser (Success) + # BadRequestError (Bad request) + # NotFoundError (Not found) + resource function post pets() returns OkUser|BadRequestError|NotFoundError { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_15_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_15_rs.bal index f9c02ed52..954f10c96 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_15_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_15_rs.bal @@ -3,6 +3,24 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - A list of pets. resource function post pets() returns Pet[] { } + # Creates a new pets. + # + # + return - A list of pets. + resource function post pets02() returns string[] { + } + # Creates a new pets. + # + # + return - A list of pets. + resource function post pets03() returns json { + } + # Creates a new pets. + # + # + return - A list of pets. + resource function post pets04() returns json { + } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_16_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_16_rs.bal index 2c25eda5a..c8e955c7d 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_16_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_16_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - A list of pets. resource function post pets() returns BadRequestError { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_19_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_19_rs.bal index 6ff673e17..179078738 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_19_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_19_rs.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - returns can be any of following types + # User (Created) + # BadRequestXml (Bad request) + # NotFoundString (Not found) resource function post pets() returns User|BadRequestXml|NotFoundString { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_20_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_20_rs.bal index 28e6515ec..af18b5cee 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_20_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_20_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - Success resource function post pets() returns string { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_21_rs.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_21_rs.bal index 28e6515ec..af18b5cee 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_21_rs.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/scenario_21_rs.bal @@ -3,6 +3,9 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # Creates a new pets. + # + # + return - Success resource function post pets() returns string { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/response/unsupportedPayload.bal b/openapi-cli/src/test/resources/generators/service/ballerina/response/unsupportedPayload.bal new file mode 100644 index 000000000..a333e4acc --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/ballerina/response/unsupportedPayload.bal @@ -0,0 +1,30 @@ +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); + +service /v1 on ep0 { + # Returns pet inventories by status + # + # + return - successful operation + resource function get store/inventory() returns json { + } + # Description + # + # + return - successful operation + resource function put store/inventory() returns json { + } + # Description + # + # + return - returns can be any of following types + # OkJsonXml (successful operation) + # BadRequestAnydata (bad request operation) + # NotFoundAnydata (bad operation) + # InternalServerErrorString (error operation) + resource function post store/inventory() returns OkJsonXml|BadRequestAnydata|NotFoundAnydata|InternalServerErrorString { + } + # Description + # + # + return - successful operation + resource function delete store/inventory() returns anydata { + } +} diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/service_gen.bal b/openapi-cli/src/test/resources/generators/service/ballerina/service_gen.bal index 534a67549..efbe11b78 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/service_gen.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/service_gen.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) resource function get pets(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/ballerina/service_gen_special_characters.bal b/openapi-cli/src/test/resources/generators/service/ballerina/service_gen_special_characters.bal index 275918168..4cbae260e 100644 --- a/openapi-cli/src/test/resources/generators/service/ballerina/service_gen_special_characters.bal +++ b/openapi-cli/src/test/resources/generators/service/ballerina/service_gen_special_characters.bal @@ -3,6 +3,12 @@ import ballerina/http; listener http:Listener ep0 = new (80, config = {host: "petstore.openapi.io"}); service /v1 on ep0 { - resource function get v3/'pet\-store/v1(int? 'limit) returns Pets|http:Response { + # List all pets + # + # + 'limit - How many items to return at one time (max 100) + # + return - returns can be any of following types + # Pets (An paged array of pets) + # http:Response (unexpected error) + resource function get v3/pet\-store/v1(int? 'limit) returns Pets|http:Response { } } diff --git a/openapi-cli/src/test/resources/generators/service/diagnostic_files/petstore_original.yaml b/openapi-cli/src/test/resources/generators/service/diagnostic_files/petstore_original.yaml new file mode 100644 index 000000000..6f96dd579 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/diagnostic_files/petstore_original.yaml @@ -0,0 +1,802 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + description: Update an existing pet by Id + operationId: updatePet + requestBody: + description: Update an existent pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: false + explode: true + schema: + type: string + default: available + enum: + - available + - pending + - sold + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: false + explode: true + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + - name: name + in: query + description: Name of pet that needs to be updated + schema: + type: string + - name: status + in: query + description: Status of pet that needs to be updated + schema: + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet + description: delete a pet + operationId: deletePet + parameters: + - name: api_key + in: header + description: '' + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}/uploadImage: + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + - name: additionalMetadata + in: query + description: Additional Metadata + required: false + schema: + type: string + requestBody: + content: + application/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - write:pets + - read:pets + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: Place a new order in the store + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Order' + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + '405': + description: Invalid input + /store/order/{orderId}: + get: + tags: + - store + summary: Find purchase order by ID + description: For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of order that needs to be fetched + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + application/xml: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + description: Created user object + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/User' + responses: + default: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: Creates list of users with given input array + operationId: createUsersWithListInput + requestBody: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: false + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: false + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + parameters: [] + responses: + default: + description: successful operation + /user/{username}: + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Update user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + requestBody: + description: Update an existent user in the store + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/User' + responses: + default: + description: successful operation + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +components: + schemas: + Order: + type: object + properties: + id: + type: integer + format: int64 + example: 10 + petId: + type: integer + format: int64 + example: 198772 + quantity: + type: integer + format: int32 + example: 7 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + example: approved + enum: + - placed + - approved + - delivered + complete: + type: boolean + xml: + name: order + Customer: + type: object + properties: + id: + type: integer + format: int64 + example: 100000 + username: + type: string + example: fehguy + address: + type: array + xml: + name: addresses + wrapped: true + items: + $ref: '#/components/schemas/Address' + xml: + name: customer + Address: + type: object + properties: + street: + type: string + example: 437 Lytton + city: + type: string + example: Palo Alto + state: + type: string + example: CA + zip: + type: string + example: '94301' + xml: + name: address + Category: + type: object + properties: + id: + type: integer + format: int64 + example: 1 + name: + type: string + example: Dogs + xml: + name: category + User: + type: object + properties: + id: + type: integer + format: int64 + example: 10 + username: + type: string + example: theUser + firstName: + type: string + example: John + lastName: + type: string + example: James + email: + type: string + example: john@email.com + password: + type: string + example: '12345' + phone: + type: string + example: '12345' + userStatus: + type: integer + description: User Status + format: int32 + example: 1 + xml: + name: user + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: tag + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + example: 10 + name: + type: string + example: doggie + category: + $ref: '#/components/schemas/Category' + photoUrls: + type: array + xml: + wrapped: true + items: + type: string + xml: + name: photoUrl + tags: + type: array + xml: + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + xml: + name: '##default' + requestBodies: + Pet: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + UserArray: + description: List of user object + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://petstore3.swagger.io/oauth/authorize + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_invalid.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_invalid.yaml new file mode 100644 index 000000000..16d18648c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_invalid.yaml @@ -0,0 +1,48 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + parameters: + - name: x-request-id + in: header + description: Unique request ID + required: true + schema: + type: integer + format: invalid_int + responses: + '200': + description: An array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_signed32.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_signed32.yaml new file mode 100644 index 000000000..b69e415b7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_integer_signed32.yaml @@ -0,0 +1,70 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Pet Store + 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: pet-store + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + parameters: + - name: x-request-id + in: header + description: Unique request ID + required: true + schema: + type: integer + format: int32 + - name: x-registration-id + in: header + description: Pet's registration ID + required: true + schema: + type: integer + format: int32 + maximum: 10000 + - name: x-microchip-id + in: header + description: Unique microchip ID + required: false + schema: + type: integer + format: int32 + minimum: 1 + - name: x-owner-id + in: header + description: Pet's owner ID + required: false + schema: + type: integer + responses: + '200': + description: An array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_record_type.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_record_type.yaml new file mode 100644 index 000000000..3e80864c0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_record_type.yaml @@ -0,0 +1,27 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: X-User + in: header + schema: + type: object + properties: + name: + type: string + department: + type: string + responses: + "200": + description: Ok diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_array_ref.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_array_ref.yaml new file mode 100644 index 000000000..7a2c2194c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_array_ref.yaml @@ -0,0 +1,33 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: X-Users + in: header + schema: + type: array + items: + $ref: '#/components/schemas/User' + responses: + "200": + description: Ok +components: + schemas: + User: + type: object + properties: + name: + type: string + department: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_object.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_object.yaml new file mode 100644 index 000000000..a418e3417 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_object.yaml @@ -0,0 +1,24 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: X-User + in: header + schema: + type: array + items: + type: object + responses: + "200": + description: Ok diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_ref.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_ref.yaml new file mode 100644 index 000000000..c2d1548ff --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_ref.yaml @@ -0,0 +1,31 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: X-User + in: header + schema: + $ref: '#/components/schemas/User' + responses: + "200": + description: Ok +components: + schemas: + User: + type: object + properties: + name: + type: string + department: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_type.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_type.yaml new file mode 100644 index 000000000..518405e0f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/header_with_invalid_type.yaml @@ -0,0 +1,22 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: X-User + in: header + schema: + type: object + responses: + "200": + description: Ok diff --git a/openapi-cli/src/test/resources/generators/service/swagger/headers/headers_with_reference.yaml b/openapi-cli/src/test/resources/generators/service/swagger/headers/headers_with_reference.yaml new file mode 100644 index 000000000..9ed17f4ae --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/headers/headers_with_reference.yaml @@ -0,0 +1,78 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /ping: + get: + operationId: operation_get_/ping + parameters: + - name: x-client + in: header + schema: + $ref: '#/components/schemas/XClient' + required: true + - name: x-content + in: header + schema: + $ref: '#/components/schemas/XContent' + - $ref: '#/components/parameters/XAPIName' + - name: x-count + in: header + required: true + schema: + $ref: '#/components/schemas/XCount' + - name: x-valid + in: header + schema: + $ref: '#/components/schemas/XValid' + - name: x-sequence + in: header + schema: + $ref: '#/components/schemas/XSequence' + - name: X-Rate + in: header + schema: + type: number + format: float + - name: X-Modified + in: header + schema: + type: boolean + nullable: true + - name: X-Client-Profiles + in: header + schema: + type: array + items: + $ref: '#/components/schemas/XClient' + responses: + "200": + description: Ok +components: + parameters: + XAPIName: + name: Consent-ID + in: header + schema: + type: string + schemas: + XClient: + type: string + XContent: + type: string + default: 'JSON' + XCount: + type: integer + XValid: + type: boolean + XSequence: + type: array + items: + type: integer diff --git a/openapi-cli/src/test/resources/generators/service/swagger/inline_record_type_request_response.yaml b/openapi-cli/src/test/resources/generators/service/swagger/inline_record_type_request_response.yaml index e1739ac34..1c6548733 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/inline_record_type_request_response.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/inline_record_type_request_response.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new user. responses: - 200: + 201: description: OK content: application/json: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/intPathParam.yaml b/openapi-cli/src/test/resources/generators/service/swagger/intPathParam.yaml new file mode 100644 index 000000000..5dcbb3e1d --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/intPathParam.yaml @@ -0,0 +1,88 @@ +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 +paths: + /store/{storeId}/users/{userId}/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: integer + format: int32 + - name: userId + in: path + required: true + description: The id of the user to retrieve + schema: + type: integer + format: int64 + - name: storeId + in: path + required: true + description: The id of the store to retrieve + schema: + type: integer + format: invalid_int + 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 + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/keywords.yaml b/openapi-cli/src/test/resources/generators/service/swagger/keywords.yaml index f401b14a8..e240b036a 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/keywords.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/keywords.yaml @@ -42,7 +42,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners.yaml b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners.yaml index ea9cb8ca2..402f89f37 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners.yaml @@ -49,7 +49,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners03.yaml b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners03.yaml index e3c5273f4..ba66e0aa1 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners03.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners03.yaml @@ -31,7 +31,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners04.yaml b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners04.yaml index 9e508fd16..495a6c169 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners04.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/listeners/petstore_listeners04.yaml @@ -20,7 +20,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/multiOperations.yaml b/openapi-cli/src/test/resources/generators/service/swagger/multiOperations.yaml index 66ee51314..59fff14cc 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/multiOperations.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/multiOperations.yaml @@ -52,7 +52,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/multiPaths.yaml b/openapi-cli/src/test/resources/generators/service/swagger/multiPaths.yaml index acbff61d0..586978fcb 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/multiPaths.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/multiPaths.yaml @@ -68,7 +68,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_invalid_schema.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_invalid_schema.yaml new file mode 100644 index 000000000..2eab84b99 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_invalid_schema.yaml @@ -0,0 +1,88 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings: + get: + description: List all the meetings that were scheduled + operationId: listMeetings + parameters: + - description: "Meeting location" + in: query + name: location + schema: + type: array + items: + $ref: '#/components/schemas/Room' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + description: "HTTP Status Code:200. List of meetings returned." +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + Room: + content: + application/xml: + schema: + $ref: '#/components/schemas/RoomObject' + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_object_schema.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_object_schema.yaml new file mode 100644 index 000000000..71e1b4df9 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_array_object_schema.yaml @@ -0,0 +1,90 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings: + get: + description: List all the meetings that were scheduled + operationId: listMeetings + parameters: + - description: "Meeting location" + in: query + name: location + schema: + type: array + items: + $ref: '#/components/schemas/Room' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + description: "HTTP Status Code:200. List of meetings returned." +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + Room: + type: object + properties: + roomNo: + type: string + seats: + type: integer + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_v31.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_v31.yaml new file mode 100644 index 000000000..90979dac1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameter_with_ref_v31.yaml @@ -0,0 +1,77 @@ +openapi: 3.1.0 +info: + title: Swagger Petstore - OpenAPI 3.1 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.1 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +paths: + /pet: + post: + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + parameters: + - $ref: "#/components/parameters/id" + - name: name + in: query + schema: + type: string + default: "doggie" + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +components: + parameters: + id: + name: id + schema: + type: integer + required: true + in: query + schemas: + Category: + type: object + properties: + name: + type: + - string + Pet: + required: + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: + - string + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_enum.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_enum.yaml new file mode 100644 index 000000000..802c421d8 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_enum.yaml @@ -0,0 +1,169 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: + default: live + enum: + - scheduled + - live + - upcoming + type: string + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + default: "available" + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + required: true + - description: Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + in: header + name: X-Date-Format + schema: + enum: + - UTC + - LOCAL + - OFFSET + - EPOCH + - LEET + - description: Time Zones of attendees + in: header + required: true + name: X-Time-Zones + schema: + type: array + items: + enum: + - IST + - GMT + - UTC + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/RoomNo' + - $ref: "#/components/parameters/responseFormat" + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + RoomNo: + default: "R5" + enum: + - R1 + - R3 + - R5 + type: string + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_invalid_ref_schema.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_invalid_ref_schema.yaml new file mode 100644 index 000000000..41c28d535 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_invalid_ref_schema.yaml @@ -0,0 +1,84 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings: + get: + description: List all the meetings that were scheduled + operationId: listMeetings + parameters: + - description: "Meeting location" + in: query + name: location + $ref: '#/components/parameters/responseFormat' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + description: "HTTP Status Code:200. List of meetings returned." +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + content: + application/xml: + schema: + $ref: '#/components/schemas/MeetingList' + schemas: + Room: + type: object + properties: + roomNo: + type: string + seats: + type: integer + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_nullable_enums.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_nullable_enums.yaml new file mode 100644 index 000000000..ad8567269 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_nullable_enums.yaml @@ -0,0 +1,154 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/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 + parameters: + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: +# default: live + enum: + - scheduled + - live + - upcoming + - null + type: string + nullable: true + - description: "Status values that need to be considered for filter" + in: query + name: status + schema: + type: array + items: + type: string + enum: + - "available" + - "pending" + - null + - description: Date time format (cf. [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) & [leettime.de](http://leettime.de/)) + in: header + name: X-Date-Format + schema: + enum: + - UTC + - LOCAL + - OFFSET + - EPOCH + - LEET + - null + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/RoomNo' + - $ref: "#/components/parameters/responseFormat" + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + - null + type: string + schemas: + RoomNo: +# How can we address when default value is there in a reusable enum + default: R5 + enum: + - R1 + - R3 + - R5 + - null + type: string + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_object_ref_schema.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_object_ref_schema.yaml new file mode 100644 index 000000000..6d14877a7 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_object_ref_schema.yaml @@ -0,0 +1,88 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings: + get: + description: List all the meetings that were scheduled + operationId: listMeetings + parameters: + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/Room' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + description: "HTTP Status Code:200. List of meetings returned." +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + Room: + type: object + properties: + roomNo: + type: string + seats: + type: integer + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_ref_schema.yaml b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_ref_schema.yaml new file mode 100644 index 000000000..1cb7338b0 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/parameters_with_ref_schema.yaml @@ -0,0 +1,163 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings: + get: + description: List all the meetings that were scheduled + operationId: listMeetings + parameters: + - description: "Meeting organizer" + in: query + name: organizer + required: true + schema: + $ref: '#/components/schemas/Organizer' + - description: "Meeting location" + in: query + name: location + schema: + $ref: '#/components/schemas/RoomNo' + - description: "Meeting Types" + in: query + required: true + name: types + schema: + type: array + items: + $ref: '#/components/schemas/MeetingTypes' + - description: "Meeting audience" + in: query + name: audience + schema: + $ref: '#/components/schemas/Audience' + - description: "Meeting remarks" + in: query + name: remarks + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Remarks' + - description: "Booking Invoice" + in: query + required: true + name: invoices + schema: + type: array + items: + $ref: '#/components/schemas/booking_invoice' +# - description: "Meeting timezone" +# in: query +# name: timezone +# schema: +# $ref: '#/components/schemas/TimeZone' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + parameters: + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + schemas: + Organizer: + type: string + Audience: + enum: + - "students" + - "professionals" + Remarks: + type: object + additionalProperties: true + # not supported currently by the http module +# TimeZone: +# type: string +# nullable: true + RoomNo: + default: "R5" + enum: + - R1 + - R3 + - R5 + type: string + MeetingTypes: + type: string + default: live + enum: + - "scheduled" + - "live" + - "upcoming" + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object + booking_invoice: + type: integer diff --git a/openapi-cli/src/test/resources/generators/service/swagger/path_param_nullable.yaml b/openapi-cli/src/test/resources/generators/service/swagger/path_param_nullable.yaml new file mode 100644 index 000000000..804a3b5cc --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/path_param_nullable.yaml @@ -0,0 +1,97 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /users/meetings/{group}: + 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 + parameters: + - description: "Employee group" + in: path + name: group + schema: + type: string + enum: + - "Admin" + - "HR" + - "Engineering" + - null + nullable: true + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingList' + 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." + tags: + - Meetings +components: + schemas: + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingObject: + properties: + 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." + type: integer + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/petstore_service.yaml b/openapi-cli/src/test/resources/generators/service/swagger/petstore_service.yaml index ea9cb8ca2..402f89f37 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/petstore_service.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/petstore_service.yaml @@ -49,7 +49,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/petstore_service_with_special_characters.yaml b/openapi-cli/src/test/resources/generators/service/swagger/petstore_service_with_special_characters.yaml index aa21331d7..c95794aeb 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/petstore_service_with_special_characters.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/petstore_service_with_special_characters.yaml @@ -49,7 +49,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/object_query.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/object_query.yaml new file mode 100644 index 000000000..488010d2b --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/object_query.yaml @@ -0,0 +1,259 @@ +openapi: 3.0.0 +servers: + # Added by API Auto Mocking Plugin + - description: SwaggerHub API Auto Mocking + url: https://virtserver.swaggerhub.com/lnash94/QueryParam/1.0.0 +info: + description: This is a simple API + version: "1.0.0" + title: Simple Inventory API +tags: + - name: admins + description: Secured Admin-only calls + - name: developers + description: Operations available to regular developers +paths: + /inventory: + get: + tags: + - developers + summary: searches inventory + operationId: searchInventory + description: | + By passing in the appropriate options, you can search for + available inventory in the system + parameters: + - in: query + name: required_query + description: 1. required query param with inline object + required: true + schema: + type: object + properties: + name: + type: string + id: + type: integer + - in: query + name: optional_query + description: 2. optional query param with inline object + required: false + schema: + type: object + properties: + rank: + type: string + id: + type: integer + - in: query + name: default_query + description: 3. default query param with inline object + schema: + type: object + properties: + limit: + type: string + id: + type: integer + default: {limit: "9", id: 9} + - in: query + name: reference_query + description: 4. reference query param + schema: + $ref: '#/components/schemas/Manufacturer' + - in: query + name: required_nullable + description: 5. required query param with inline object and nullable true + required: true + schema: + nullable: true + type: object + properties: + name: + type: string + id: + type: integer + - in: query + name: optional_nullable + description: 6. optional query param with inline and nullable object + required: false + schema: + nullable: true + type: object + properties: + rank: + type: string + id: + type: integer + - in: query + name: default_nullable + description: 7. default query param with inline and nullable object + schema: + nullable: true + type: object + properties: + limit: + type: string + id: + type: integer + default: {limit: "9", id: 9} + - in: query + name: reference_nullable + description: 8. reference_nullable query param won't consider nullable details when it has reference in swagger + schema: + nullbale: true + $ref: '#/components/schemas/Manufacturer' + responses: + '200': + description: search results matching criteria + '400': + description: bad input parameter + post: + tags: + - admins + summary: adds an inventory item + operationId: addInventory + description: Adds an item to the system + parameters: + - in: query + name: required_query + description: 9. required query param with inline object including additional properties with reference. + required: true + schema: + type: object + additionalProperties: + $ref: '#/components/schemas/InventoryItem' + - in: query + name: optional_query + description: 10. optional query param with inline object including additional properties integer value. + required: false + schema: + type: object + additionalProperties: + type: integer + - in: query + name: object_nullable + description: 11. nullable required query param with inline object including additional properties + schema: + nullable: true + type: object + additionalProperties: + $ref: '#/components/schemas/InventoryItem' + - in: query + name: skip_nullable + description: 12. nullable optional query param with inline object including additional properties + required: false + schema: + nullable: true + type: object + additionalProperties: + type: integer + - in: query + name: add_false + description: 13. nullable optional query param with inline object including additional properties. + schema: + nullable: true + type: object + properties: + name: + type: string + additionalProperties: false + responses: + '201': + description: item created + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/InventoryItem' + description: Inventory item to add + put: + description: "Update inventory" + operationId: updateInvent + parameters: + - in: query + description: 14. object query parameter with additional property with primitive value + name: primitive + schema: + type: object + additionalProperties: + $ref: '#/components/schemas/PrimitiveValues' + responses: + '201': + description: Created + delete: + description: "Update inventory" + operationId: deleteInvent + parameters: + - in: query + name: arrayRecord + description: 15. Query parameter with object array + schema: + type: array + items: + type: object + $ref: '#/components/schemas/InventoryItem' + responses: + '201': + description: Created + /inventory02: + put: + description: "Update inventory" + operationId: updateInvent02 + parameters: + - in: query + name: additionalArray + description: 16. Query parameter with record opens with record array + schema: + type: object + additionalProperties: + type: array + items: + type: object + $ref: '#/components/schemas/InventoryItem' + responses: + '201': + description: Created +components: + schemas: + PrimitiveValues: + type: integer + enum: + - 0 + - 1 + InventoryItem: + type: object + required: + - id + - name + - manufacturer + - releaseDate + properties: + id: + type: string + format: uuid + example: d290f1ee-6c54-4b01-90e6-d701748f0851 + name: + type: string + example: Widget Adapter + releaseDate: + type: string + format: date-time + example: '2016-08-29T09:12:33.001Z' + manufacturer: + $ref: '#/components/schemas/Manufacturer' + Manufacturer: + required: + - name + properties: + name: + type: string + example: ACME Corporation + homePage: + type: string + format: url + example: 'https://www.acme-corp.com' + phone: + type: string + example: 408-867-5309 + type: object diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_01.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_01.yaml index ecacf14e4..8b790c491 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/query/query_01.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_01.yaml @@ -18,7 +18,6 @@ paths: required: true schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_02.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_02.yaml index e450d2e0f..08f0600ff 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/query/query_02.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_02.yaml @@ -20,7 +20,6 @@ paths: type: array items: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_06.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_06.yaml index 3fe930bb6..a51a4d154 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/query/query_06.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_06.yaml @@ -20,7 +20,6 @@ paths: nullable: true items: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_09.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_09.yaml index 2d7ef6d85..7e28bf695 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/query/query_09.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_09.yaml @@ -18,7 +18,6 @@ paths: schema: type: integer default: 10 - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_11.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_11.yaml index ab91c7d36..bf832ba56 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/query/query_11.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_11.yaml @@ -19,7 +19,6 @@ paths: schema: type: integer nullable: true - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_invalid.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_invalid.yaml new file mode 100644 index 000000000..ebc58bb54 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_invalid.yaml @@ -0,0 +1,40 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstoe +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /pets: + get: + operationId: listPets + parameters: + - name: limit + in: query + required: true + schema: + type: integer + format: int_invalid + - name: offset + in: query + schema: + type: integer + format: int_invalid + - name: next + in: query + required: true + schema: + type: integer + responses: + '200': + description: An paged array of pets + content: + application/json: + schema: + type: integer + format: int32 + diff --git a/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_signed32.yaml b/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_signed32.yaml new file mode 100644 index 000000000..4ebbe5b1f --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/query/query_integer_signed32.yaml @@ -0,0 +1,34 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstoe +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi +paths: + /pets: + get: + operationId: listPets + parameters: + - name: limit + in: query + required: true + schema: + type: integer + format: int32 + - name: offset + in: query + schema: + type: integer + format: int32 + - name: next + in: query + required: true + schema: + type: integer + responses: + '200': + description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/additional_property.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/additional_property.yaml new file mode 100644 index 000000000..a56c0bccd --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/additional_property.yaml @@ -0,0 +1,128 @@ +openapi: 3.0.1 +info: + title: APITest + contact: + name: Samuel Apolion Benevenuto + version: v1 +paths: + /api/HistoricoSimulacao/AddHistorico: + post: + tags: + - HistoricoSimulacao + requestBody: + content: + application/json-patch+json: + schema: + type: object + additionalProperties: #addtionalProperties with primitive types + type: string + application/json: + schema: + type: object + additionalProperties: #addtionalProperties with reference + $ref: '#/components/schemas/HistoricoSimulacaoViewModel' + application/path+json: + schema: + type: object + additionalProperties: #addtionalProperties with reference + type: object + additionalProperties: + type: string + responses: + '200': + description: Success + x-auth-type: None + x-throttling-tier: Unlimited + /api/Mailing/AddContact: + post: + tags: + - Mailing + requestBody: + content: + application/json-patch+json: + schema: + type: object + properties: + name: + type: string + additionalProperties: #Object schema with properties and additionalProperties fields + type: integer + application/json: + schema: + type: object + properties: + name: + type: string + additionalProperties: #Object schema with properties and additionalProperties with reference fields + $ref: '#/components/schemas/MailingViewModel' + responses: + '200': + description: Success + x-auth-type: None + x-throttling-tier: Unlimited + put: + tags: + - Mailing + requestBody: + content: + application/json-patch+json: + schema: + type: object + properties: + name: + type: string + additionalProperties: #Object schema with properties and additionalProperties fields + allOf: + - type: integer + application/json: + schema: + type: object + properties: + name: + type: string + additionalProperties: #Object schema with properties and additionalProperties with reference fields + oneOf: + - type: integer + - $ref: '#/components/schemas/MailingViewModel' + responses: + '200': + description: Success + x-auth-type: None + x-throttling-tier: Unlimited +components: + schemas: + HistoricoSimulacaoViewModel: + type: object + properties: + email: + type: string + nullable: true + data: + type: string + format: date-time + nullable: true + step: + type: string + nullable: true + descricao: + type: string + nullable: true + additionalProperties: false + MailingViewModel: + type: object + properties: + name: + type: string + nullable: true + email: + type: string + nullable: true + optPhoneNumber: + type: boolean + phoneNumber: + type: string + nullable: true + motivoRecusa: + type: string + nullable: true + additionalProperties: false diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/any_of.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/any_of.yaml new file mode 100644 index 000000000..f5df37997 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/any_of.yaml @@ -0,0 +1,43 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /pets03: + post: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets1 + requestBody: + content: + "application/json": + schema: + anyOf: + - $ref: "#/components/schemas/Dog" + - $ref: "#/components/schemas/Cat" + responses: + "201": + description: OK +components: + schemas: + Dog: + type: object + required: + - userName + properties: + userName: + type: string + kind: + type: string + Cat: + type: object + required: + - userName + properties: + name: + type: string + kind: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multipart_form_data.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multipart_form_data.yaml new file mode 100644 index 000000000..b60add221 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multipart_form_data.yaml @@ -0,0 +1,31 @@ +openapi: 3.0.1 +info: + title: testInlineRequestBody + version: 1.0.0 +paths: + /user: + post: + summary: Post operation for the path /user + operationId: addUser + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + userName: + description: User Name + type: string + userPhone: + description: User Phone Number + type: string + required: + - userName + - userPhone + responses: + 200: + description: Successful + content: + application/json: + example: Ok +components: {} diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multiple_content.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multiple_content.yaml new file mode 100644 index 000000000..7a398a808 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/multiple_content.yaml @@ -0,0 +1,120 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /pets: + post: + summary: Add a new pet + responses: + 200: + description: OK + requestBody: + description: Optional description in *Markdown* + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PetForm' + text/plain: + schema: + type: string + put: + summary: Add a new pet + responses: + 200: + description: OK + requestBody: + description: Optional description in *Markdown* + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/zip: + schema: + $ref: '#/components/schemas/PetForm' + text/plain: + schema: + type: string + /pets02: + post: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + requestBody: + content: + "application/json": + schema: + $ref: "#/components/schemas/Pet" + "application/xml": + schema: + $ref: "#/components/schemas/Pet" + responses: + "201": + description: OK +components: + schemas: + User: + type: object + required: + - userName + properties: + userName: + type: string + firstName: + type: string + lastName: + type: string + Pet: + type: object + required: + - userName + properties: + userName: + type: string + firstName: + type: string + lastName: + type: string + PetForm: + type: object + required: + - userName + properties: + userName: + type: string + firstName: + type: string + lastName: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/oneOf_request_body.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/oneOf_request_body.yaml index ec33dcba2..91215df2f 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/oneOf_request_body.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/oneOf_request_body.yaml @@ -1,25 +1,27 @@ openapi: 3.0.1 info: - title: Storage Space + title: Pets store license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.0 paths: - /storageSpaces01: + /pet: put: - summary: "Unsupported scenario 01: Customised request body with empty schema" + summary: "scenario 01: Request body is with oneOf schema for application/json" operationId: putKey requestBody: - description: "Customised request body with empty schema" content: - application/snowflake+json: - schema: {} + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/Dog" + - $ref: "#/components/schemas/Cat" responses: 200: description: Successful operation. post: - summary: "Unsupported scenario 02: Customised request body with oneOf schema" + summary: "scenario 02: Customised request body with oneOf schema" operationId: post requestBody: description: "Customised request body" @@ -27,14 +29,14 @@ paths: application/snowflake+json: schema: oneOf: - - $ref: "#/components/schemas/HandleRequest_RequestBody" - - $ref: "#/components/schemas/HandleRequest_RequestBody02" + - $ref: "#/components/schemas/Dog" + - $ref: "#/components/schemas/Bird" responses: 200: description: Successful operation. - /storageSpaces02: + /pet02: post: - summary: "Unsupported scenario 03: Request body with oneOf schema" + summary: "scenario 03: Request body with oneOf schema with application/xml" operationId: postKey requestBody: description: "Ballerina not support for oneOf data type in request body" @@ -42,13 +44,13 @@ paths: application/xml: schema: oneOf: - - $ref: "#/components/schemas/HandleRequest_RequestBody" - - $ref: "#/components/schemas/HandleRequest_RequestBody02" + - $ref: "#/components/schemas/Dog" + - $ref: "#/components/schemas/Cat" responses: 200: description: Successful operation. put: - summary: "Unsupported scenario 04: Request body with oneOf schema with integer, number" + summary: "scenario 04: Request body with oneOf schema with integer, number (primitives)" operationId: put requestBody: description: "Ballerina not support for oneOf data type in request body" @@ -62,47 +64,68 @@ paths: responses: 200: description: Successful operation. - /storageSpaces/{name}: + /pet/{name}: put: - summary: Put key value + summary: "scenarios05: requestBody is with oneOf array type" operationId: key parameters: - name: name in: path - description: name of the storage space required: true schema: type: string requestBody: - description: Value to be added + description: "" content: - application/json: + text/plain: + schema: + oneOf: + - type: array + items: + oneOf: + - type: string + - type: integer + - type: number + responses: + 200: + description: Successful operation. + 400: + description: Invalid storage space name supplied + /pet04: + post: + operationId: postKey04 + requestBody: + description: "scenario04: Media type is with not main standard type. " + content: + application/zip: schema: oneOf: - type: string - type: integer - type: number - - type: object responses: 200: description: Successful operation. - 400: - description: Invalid storage space name supplied components: schemas: - HandleRequest_RequestBody: - title: Request/Response handler + Dog: type: object properties: - headers: + name: type: string - body: + age: type: string - HandleRequest_RequestBody02: - title: Request/Response handler + Cat: type: object properties: - headers: + name: + type: string + kind: type: string - body: + Bird: + type: object + properties: + name: type: string + isFly: + type: boolean diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario01_02_rb.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario01_02_rb.yaml index 0eac80bff..677c2ff76 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario01_02_rb.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/scenario01_02_rb.yaml @@ -35,6 +35,18 @@ paths: application/octet-stream: schema: type: string + /payment: + post: + summary: Creates a new payment. + responses: + 200: + description: OK + requestBody: + description: Details of the pet to be purchased + content: + application/octet-stream: + schema: + $ref: '#/components/schemas/Pet' components: schemas: User: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/requestBody/unhandled_media_type.yaml b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/unhandled_media_type.yaml new file mode 100644 index 000000000..5604c94de --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/requestBody/unhandled_media_type.yaml @@ -0,0 +1,90 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + post: + summary: Returns a list of users. + description: Optional extended description in Markdown. + requestBody: + content: + multipart/mixed: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + type: object + properties: { } + historyMetadata: + description: metadata in XML format + type: object + properties: { } + profileImage: + type: string + format: binary + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + responses: + '200': + description: OK + put: + summary: Update a user image. + requestBody: + content: + image/png: + schema: + type: string + format: binary + responses: + 200: + description: OK + + + /users/{id}: + put: + summary: Returns a user by ID. + description: Optional extended description in Markdown. + parameters: + - name: id + in: path + description: ID of user to fetch + required: true + schema: + type: string + format: uuid + requestBody: + content: + application/epub+zip: + schema: + $ref: '#/components/schemas/User' + responses: + '200': + description: OK + +components: + schemas: + User: + type: object + properties: + id: + type: string + format: uuid + name: + type: string + address: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/empty_response.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/empty_response.yaml new file mode 100644 index 000000000..1603b5b6c --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/empty_response.yaml @@ -0,0 +1,25 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://localhost:9090/petstore/v1 +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 + responses: {} diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/multiline_return_description.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/multiline_return_description.yaml new file mode 100644 index 000000000..1ed486684 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/multiline_return_description.yaml @@ -0,0 +1,101 @@ +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: + description: | + Show a list of pets in the system. + Pet can be in any category + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: | + How many items to return at one time (max 100). + Min is 1 + required: false + schema: + type: integer + responses: + '200': + description: | + OK. + 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" +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/openapi-cli/src/test/resources/generators/service/swagger/response/path_with_special_characters.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/path_with_special_characters.yaml index 7f457189a..5c8a857ad 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/path_with_special_characters.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/path_with_special_characters.yaml @@ -49,7 +49,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/post_method.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/post_method.yaml new file mode 100644 index 000000000..a4e1680ef --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/post_method.yaml @@ -0,0 +1,66 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /user: + post: + summary: Creates a new user. + responses: + 200: + description: OK + /user02: + post: + summary: post method with 201 + operationId: post201 + responses: + 201: + description: Created + /user03: + post: + summary: post method with 201 with content + responses: + 201: + description: Created + content: + text/plain: + schema: + type: string + /user04: + post: + summary: post method with 201,200 + operationId: post + responses: + 201: + description: Created + content: + text/plain: + schema: + type: string + 200: + description: ok + content: + text/plain: + schema: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/reference_response.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/reference_response.yaml new file mode 100644 index 000000000..1be774718 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/reference_response.yaml @@ -0,0 +1,68 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Gets a list of users. + responses: + '401': + $ref: '#/components/responses/Unauthorized' + /users/{id}: + get: + summary: Gets a user by ID. + parameters: + - in: path + name: id + schema: + type: integer + required: true + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/User' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' +# Descriptions of common components +components: + responses: + NotFound: + description: The specified resource was not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + schemas: + # Schema for error response body + Error: + type: object + properties: + code: + type: string + message: + type: string + required: + - code + - message + User: + type: object + properties: + name: + type: string + age: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/response_codes.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/response_codes.yaml index 07c756f2a..5bd9bec01 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/response_codes.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/response_codes.yaml @@ -18,6 +18,10 @@ paths: description: Continue "101": description: SwitchingProtocols + "102": + description: Processing + "103": + description: EarlyHints "200": description: Ok "201": @@ -30,6 +34,12 @@ paths: description: NoContent "206": description: PartialContent + "207": + description: MultiStatus + "208": + description: AlreadyReported + "226": + description: IMUsed "300": description: MultipleChoices "301": @@ -80,12 +90,26 @@ paths: description: RangeNotSatisfiable "417": description: ExpectationFailed + "421": + description: MisDirectedRequest + "422": + description: UnProcessableEntity + "423": + description: Locked + "424": + description: FailedDependency + "425": + description: TooEarly "426": description: UpgradeRequired + "428": + description: PredictionRequired "429": description: TooManyRequests "431": description: RequestHeaderFieldsTooLarge + "451": + description: UnavailableDueToLegalReasons "500": description: InternalServerError "501": @@ -96,4 +120,14 @@ paths: description: ServiceUnavailable "505": description: HttpVersionNotSupported + "506": + description: VariantAlsoNegotiates + "507": + description: InsufficientStorage + "508": + description: LoopDetected + "510": + description: NotExtended + "511": + description: NetworkAuthorizationRequired components: {} diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/response_has_additional_properties.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/response_has_additional_properties.yaml new file mode 100644 index 000000000..dec11dd94 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/response_has_additional_properties.yaml @@ -0,0 +1,115 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + properties: + name: + type: string + age: + type: integer + additionalProperties: + type: integer + format: int32 + /store/inventory02: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory02 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: object + properties: + id: + type: integer + age: + type: integer + text/plain: + schema: + type: string + /store/inventory03: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory03 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: object + additionalProperties: + type: object + properties: + name: + type: string + place: + type: string + /store/inventory04: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory04 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + $ref: "#/components/schemas/User" + /store/inventory05: + get: + tags: + - store + operationId: getInventory05 + responses: + "400": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + $ref: "#/components/schemas/User" +components: + schemas: + User: + properties: + name: + type: string + id: + type: integer diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_03_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_03_rs.yaml index 9051e6dd5..9456d92d0 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_03_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_03_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new user. responses: - 200: + 201: description: OK content: application/json: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_07_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_07_rs.yaml index 06b2f9e40..0377fb8db 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_07_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_07_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: A list of pets content: application/json: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_08_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_08_rs.yaml index d16f26949..9dabd9e16 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_08_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_08_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: A User object content: application/json: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_10_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_10_rs.yaml index 6b772b6a1..d09c5e2de 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_10_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_10_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: A User object content: image/jpeg: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_11_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_11_rs.yaml index bfa181fe2..d3eef08ce 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_11_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_11_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: A JSON object containing pet information content: application/json: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_15_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_15_rs.yaml index 25802ee74..de96bb65b 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_15_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_15_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: A list of pets. content: application/json: @@ -36,7 +36,44 @@ paths: type: array items: $ref: '#/components/schemas/Pet' - + /pets02: + post: + summary: Creates a new pets. + responses: + '201': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + type: string + /pets03: + post: + summary: Creates a new pets. + responses: + '201': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + type: object + additionalProperties: {} + /pets04: + post: + summary: Creates a new pets. + responses: + '201': + description: A list of pets. + content: + application/snowflake+json: + schema: + type: array + items: + type: object + additionalProperties: { } components: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_19_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_19_rs.yaml index 1b9e3fc0d..c1e54361d 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_19_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_19_rs.yaml @@ -28,8 +28,8 @@ paths: post: summary: Creates a new pets. responses: - '200': - description: Success + '201': + description: Created content: application/json: schema: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_20_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_20_rs.yaml index e906db713..aa4ba6591 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_20_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_20_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: Success content: text/html: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_21_rs.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_21_rs.yaml index 860517522..92faae705 100644 --- a/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_21_rs.yaml +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/scenario_21_rs.yaml @@ -28,7 +28,7 @@ paths: post: summary: Creates a new pets. responses: - '200': + '201': description: Success content: text/csv: diff --git a/openapi-cli/src/test/resources/generators/service/swagger/response/unsupportedPayloadType.yaml b/openapi-cli/src/test/resources/generators/service/swagger/response/unsupportedPayloadType.yaml new file mode 100644 index 000000000..dc4a08ed1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/response/unsupportedPayloadType.yaml @@ -0,0 +1,109 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: "id_01" + responses: + "200": + description: successful operation + content: + application/json: + example: + put: + tags: + - store + - pet + operationId: "id_02" + responses: + "200": + description: successful operation + content: + application/snowflake+json: + example: + delete: + tags: + - store + - pet + operationId: "id_03" + responses: + "200": + description: successful operation + content: + application/json: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + application/zip: + example: + application/zip_0: + example: + post: + tags: + - store + - pet + operationId: "id_04" + responses: + "200": + description: successful operation + content: + application/json: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "400": + description: bad request operation + content: + application/json+v: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "404": + description: bad operation + content: + application/json+v: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "500": + description: error operation + content: + application/json: + schema: + type: string diff --git a/openapi-cli/src/test/resources/generators/service/swagger/wildcard.yaml b/openapi-cli/src/test/resources/generators/service/swagger/wildcard.yaml new file mode 100644 index 000000000..845793cc1 --- /dev/null +++ b/openapi-cli/src/test/resources/generators/service/swagger/wildcard.yaml @@ -0,0 +1,93 @@ +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/my: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + description: "Request to add a pet" + content: + '*/*': + schema: + $ref: "#/components/schemas/Pets" + responses: + '200': + description: Successful operation + content: + '*/*': + schema: + type: array + items: + description: "Pet records" + + +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/openapi-cli/src/test/resources/multiMethodResources.yaml b/openapi-cli/src/test/resources/multiMethodResources.yaml index a72cb6888..2797bf0bd 100644 --- a/openapi-cli/src/test/resources/multiMethodResources.yaml +++ b/openapi-cli/src/test/resources/multiMethodResources.yaml @@ -3,7 +3,7 @@ info: title: serviceName version: 1.0.0 servers: -- url: /serviceName + - url: http://petstore.openapi.io paths: /user: get: diff --git a/openapi-cli/src/test/resources/multiQueryParam.yaml b/openapi-cli/src/test/resources/multiQueryParam.yaml index 4b7f21373..80e335e1f 100644 --- a/openapi-cli/src/test/resources/multiQueryParam.yaml +++ b/openapi-cli/src/test/resources/multiQueryParam.yaml @@ -35,7 +35,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: pet response diff --git a/openapi-cli/src/test/resources/noOperationId.yaml b/openapi-cli/src/test/resources/noOperationId.yaml index c6d19e899..ef33234c2 100644 --- a/openapi-cli/src/test/resources/noOperationId.yaml +++ b/openapi-cli/src/test/resources/noOperationId.yaml @@ -3,7 +3,7 @@ info: title: serviceName version: 1.0.0 servers: -- url: /serviceName + - url: http://petstore.openapi.io paths: /user: get: diff --git a/openapi-cli/src/test/resources/no_schema_with_type_bal.yaml b/openapi-cli/src/test/resources/no_schema_with_type_bal.yaml new file mode 100644 index 000000000..5df616394 --- /dev/null +++ b/openapi-cli/src/test/resources/no_schema_with_type_bal.yaml @@ -0,0 +1,69 @@ +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: + '204': + 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: + type: string + post: + summary: Create a pet + operationId: createPet + tags: + - pets + responses: + '201': + description: Null response diff --git a/openapi-cli/src/test/resources/nonEmptyPath.yaml b/openapi-cli/src/test/resources/nonEmptyPath.yaml index 27a058b29..3704ec3a8 100644 --- a/openapi-cli/src/test/resources/nonEmptyPath.yaml +++ b/openapi-cli/src/test/resources/nonEmptyPath.yaml @@ -3,7 +3,7 @@ info: title: serviceName version: 1.0.0 servers: -- url: /serviceName + - url: http://petstore.openapi.io paths: /user: get: diff --git a/openapi-cli/src/test/resources/non_constraint_import.yaml b/openapi-cli/src/test/resources/non_constraint_import.yaml new file mode 100644 index 000000000..04cbbab57 --- /dev/null +++ b/openapi-cli/src/test/resources/non_constraint_import.yaml @@ -0,0 +1,46 @@ +openapi: 3.0.1 +info: + title: V4 + version: 0.1.0 +servers: + - url: "{server}:{port}/v4" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /pet: + post: + operationId: operation_post_/pet + responses: + "202": + description: Accepted + get: + tags: + - pets + operationId: getPet + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" +components: + schemas: + User: + type: object + properties: + name: + type: string + maxLength: 10 + age: + type: integer + Pet: + type: object + properties: + name: + type: string + owned_by: + type: string diff --git a/openapi-cli/src/test/resources/petstore.yaml b/openapi-cli/src/test/resources/petstore.yaml index 78b123ec2..683f84087 100644 --- a/openapi-cli/src/test/resources/petstore.yaml +++ b/openapi-cli/src/test/resources/petstore.yaml @@ -46,7 +46,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets @@ -155,6 +154,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/petstore.yml b/openapi-cli/src/test/resources/petstore.yml index bfc24adca..30f060207 100644 --- a/openapi-cli/src/test/resources/petstore.yml +++ b/openapi-cli/src/test/resources/petstore.yml @@ -161,6 +161,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/petstoreOperation.yaml b/openapi-cli/src/test/resources/petstoreOperation.yaml index 38eaa0d7c..ba623deef 100644 --- a/openapi-cli/src/test/resources/petstoreOperation.yaml +++ b/openapi-cli/src/test/resources/petstoreOperation.yaml @@ -51,7 +51,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/petstoreTag.yaml b/openapi-cli/src/test/resources/petstoreTag.yaml index 38eaa0d7c..ba623deef 100644 --- a/openapi-cli/src/test/resources/petstoreTag.yaml +++ b/openapi-cli/src/test/resources/petstoreTag.yaml @@ -51,7 +51,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/petstore_catch_all_path.yaml b/openapi-cli/src/test/resources/petstore_catch_all_path.yaml new file mode 100644 index 000000000..59e851048 --- /dev/null +++ b/openapi-cli/src/test/resources/petstore_catch_all_path.yaml @@ -0,0 +1,213 @@ +openapi: 3.0.3 +info: + title: OpenApi Petstore + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /*: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: query + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + - petstore_auth: + - write:pets + - read:pets + /pet: + put: + tags: + - pet + summary: Update an existing pet + description: Update an existing pet by Id + operationId: updatePet + requestBody: + description: Update an existent pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets +components: + schemas: + Category: + type: object + properties: + id: + type: integer + format: int64 + example: 1 + name: + type: string + example: Dogs + xml: + name: category + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: tag + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + example: 10 + name: + type: string + example: doggie + category: + $ref: '#/components/schemas/Category' + photoUrls: + type: array + xml: + wrapped: true + items: + type: string + xml: + name: photoUrl + tags: + type: array + xml: + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://petstore3.swagger.io/oauth/authorize + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header \ No newline at end of file diff --git a/openapi-cli/src/test/resources/petstore_nullable_false.yaml b/openapi-cli/src/test/resources/petstore_nullable_false.yaml index 659e98079..efc4e8f10 100644 --- a/openapi-cli/src/test/resources/petstore_nullable_false.yaml +++ b/openapi-cli/src/test/resources/petstore_nullable_false.yaml @@ -159,6 +159,5 @@ components: properties: code: type: integer - format: int32 message: type: string diff --git a/openapi-cli/src/test/resources/petstore_original.yaml b/openapi-cli/src/test/resources/petstore_original.yaml new file mode 100644 index 000000000..6f96dd579 --- /dev/null +++ b/openapi-cli/src/test/resources/petstore_original.yaml @@ -0,0 +1,802 @@ +openapi: 3.0.3 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + _If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_ + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.11 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: + - url: https://petstore3.swagger.io/api/v3 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io + - name: store + description: Access to Petstore orders + externalDocs: + description: Find out more about our store + url: http://swagger.io + - name: user + description: Operations about user +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + description: Update an existing pet by Id + operationId: updatePet + requestBody: + description: Update an existent pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: false + explode: true + schema: + type: string + default: available + enum: + - available + - pending + - sold + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: false + explode: true + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + - name: name + in: query + description: Name of pet that needs to be updated + schema: + type: string + - name: status + in: query + description: Status of pet that needs to be updated + schema: + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet + description: delete a pet + operationId: deletePet + parameters: + - name: api_key + in: header + description: '' + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}/uploadImage: + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + - name: additionalMetadata + in: query + description: Additional Metadata + required: false + schema: + type: string + requestBody: + content: + application/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - write:pets + - read:pets + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: Place a new order in the store + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/Order' + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + '405': + description: Invalid input + /store/order/{orderId}: + get: + tags: + - store + summary: Find purchase order by ID + description: For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of order that needs to be fetched + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + application/xml: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + description: Created user object + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/User' + responses: + default: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: Creates list of users with given input array + operationId: createUsersWithListInput + requestBody: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: false + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: false + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + parameters: [] + responses: + default: + description: successful operation + /user/{username}: + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Update user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + requestBody: + description: Update an existent user in the store + content: + application/json: + schema: + $ref: '#/components/schemas/User' + application/xml: + schema: + $ref: '#/components/schemas/User' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/User' + responses: + default: + description: successful operation + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +components: + schemas: + Order: + type: object + properties: + id: + type: integer + format: int64 + example: 10 + petId: + type: integer + format: int64 + example: 198772 + quantity: + type: integer + format: int32 + example: 7 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + example: approved + enum: + - placed + - approved + - delivered + complete: + type: boolean + xml: + name: order + Customer: + type: object + properties: + id: + type: integer + format: int64 + example: 100000 + username: + type: string + example: fehguy + address: + type: array + xml: + name: addresses + wrapped: true + items: + $ref: '#/components/schemas/Address' + xml: + name: customer + Address: + type: object + properties: + street: + type: string + example: 437 Lytton + city: + type: string + example: Palo Alto + state: + type: string + example: CA + zip: + type: string + example: '94301' + xml: + name: address + Category: + type: object + properties: + id: + type: integer + format: int64 + example: 1 + name: + type: string + example: Dogs + xml: + name: category + User: + type: object + properties: + id: + type: integer + format: int64 + example: 10 + username: + type: string + example: theUser + firstName: + type: string + example: John + lastName: + type: string + example: James + email: + type: string + example: john@email.com + password: + type: string + example: '12345' + phone: + type: string + example: '12345' + userStatus: + type: integer + description: User Status + format: int32 + example: 1 + xml: + name: user + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: tag + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + example: 10 + name: + type: string + example: doggie + category: + $ref: '#/components/schemas/Category' + photoUrls: + type: array + xml: + wrapped: true + items: + type: string + xml: + name: photoUrl + tags: + type: array + xml: + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + xml: + name: '##default' + requestBodies: + Pet: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + UserArray: + description: List of user object + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://petstore3.swagger.io/oauth/authorize + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/openapi-cli/src/test/resources/petstore_swagger.yaml b/openapi-cli/src/test/resources/petstore_swagger.yaml new file mode 100644 index 000000000..9dfb91587 --- /dev/null +++ b/openapi-cli/src/test/resources/petstore_swagger.yaml @@ -0,0 +1,682 @@ +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters." + version: "1.0.0" + title: "Swagger Petstore 2.0" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +tags: + - name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" + - name: "store" + description: "Access to Petstore orders" + - name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: + - "https" + - "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + "405": + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + "400": + description: "Invalid ID supplied" + "404": + description: "Pet not found" + "405": + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "findPetsByStatus" + produces: + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + enum: + - "available" + - "pending" + - "sold" + default: "available" + collectionFormat: "multi" + responses: + "200": + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + "400": + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + "200": + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + "400": + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + deprecated: true + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "getPetById" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + required: true + type: "integer" + format: "int64" + responses: + "200": + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + "400": + description: "Invalid ID supplied" + "404": + description: "Pet not found" + security: + - api_key: [] + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + "405": + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/json" + parameters: + - name: "api_key" + in: "header" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + "400": + description: "Invalid ID supplied" + "404": + description: "Pet not found" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + "200": + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + parameters: [] + responses: + "200": + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + responses: + "200": + description: "successful operation" + schema: + $ref: "#/definitions/Order" + "400": + description: "Invalid Order" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 10.0 + minimum: 1.0 + format: "int64" + responses: + "200": + description: "successful operation" + schema: + $ref: "#/definitions/Order" + "400": + description: "Invalid ID supplied" + "404": + description: "Order not found" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors" + operationId: "deleteOrder" + produces: + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "integer" + minimum: 1.0 + format: "int64" + responses: + "400": + description: "Invalid ID supplied" + "404": + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + responses: + "200": + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when token expires" + "400": + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + "200": + description: "successful operation" + schema: + $ref: "#/definitions/User" + "400": + description: "Invalid username supplied" + "404": + description: "User not found" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/json" + parameters: + - name: "username" + in: "path" + description: "name that need to be updated" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + "400": + description: "Invalid user supplied" + "404": + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + "400": + description: "Invalid username supplied" + "404": + description: "User not found" +securityDefinitions: + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" +definitions: + Order: + type: "object" + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + default: false + xml: + name: "Order" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + User: + type: "object" + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Pet: + type: "object" + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" \ No newline at end of file diff --git a/openapi-cli/src/test/resources/petstore_swagger_1.2.json b/openapi-cli/src/test/resources/petstore_swagger_1.2.json new file mode 100644 index 000000000..8067bda0d --- /dev/null +++ b/openapi-cli/src/test/resources/petstore_swagger_1.2.json @@ -0,0 +1,465 @@ +{ + "authorizations": { + "apiKey": { + "type": "apiKey", + "passAs": "header", + "keyname": "api_key" + }, + "oauth2": { + "type": "oauth2", + "scopes": [ + { + "scope": "email", + "description": "Access to your email address" + }, + { + "scope": "pets", + "description": "Access to your pets" + } + ], + "grantTypes": { + "implicit": { + "loginEndpoint": { + "url": "http://petstore.swagger.io/oauth/dialog" + }, + "tokenName": "access_token" + }, + "authorization_code": { + "tokenRequestEndpoint": { + "url": "http://petstore.swagger.io/oauth/requestToken", + "clientIdName": "client_id", + "clientSecretName": "client_secret" + }, + "tokenEndpoint": { + "url": "http://petstore.swagger.io/oauth/token", + "tokenName": "access_code" + } + } + } + } + }, + "apiVersion": "1.0.0", + "swaggerVersion": "1.2", + "basePath": "http://petstore.swagger.io/api", + "produces": [ + "application/json", + "application/xml", + "text/plain", + "text/html" + ], + "info": { + "title": "Swagger Sample App", + "description": "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.io or on irc.freenode.net, #swagger. For this sample,\n you can use the api key \"special-key\" to test the authorization filters", + "termsOfServiceUrl": "http://swagger.io/terms/", + "contact": "apiteam@swagger.io", + "license": "Apache 2.0", + "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "apis": [ + { + "path": "/pet/{petId}", + "operations": [ + { + "method": "GET", + "summary": "Find pet by ID", + "notes": "Returns a pet based on ID", + "type": "Pet", + "nickname": "getPetById", + "authorizations": {}, + "parameters": [ + { + "name": "petId", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "format": "int64", + "paramType": "path", + "minimum": "1.0", + "maximum": "100000.0" + } + ], + "responseMessages": [ + { + "code": 400, + "message": "Invalid ID supplied" + }, + { + "code": 404, + "message": "Pet not found" + } + ] + }, + { + "method": "PATCH", + "summary": "partial updates to a pet", + "notes": "", + "type": "array", + "items": { + "$ref": "Pet" + }, + "nickname": "partialUpdate", + "produces": [ + "application/json", + "application/xml" + ], + "consumes": [ + "application/json", + "application/xml" + ], + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, + "parameters": [ + { + "name": "petId", + "type": "string", + "description": "ID of pet that needs to be fetched", + "required": true, + "paramType": "path" + }, + { + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "type": "Pet", + "paramType": "body" + } + ], + "responseMessages": [ + { + "code": 400, + "message": "Invalid tag value" + } + ] + }, + { + "method": "POST", + "summary": "Updates a pet in the store with form data", + "notes": "", + "type": "void", + "nickname": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, + "parameters": [ + { + "name": "petId", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string", + "paramType": "path" + }, + { + "name": "name", + "description": "Updated name of the pet", + "required": false, + "type": "string", + "paramType": "form" + }, + { + "name": "status", + "description": "Updated status of the pet", + "required": false, + "type": "string", + "paramType": "form" + } + ], + "responseMessages": [ + { + "code": 405, + "message": "Invalid input" + } + ] + }, + { + "method": "DELETE", + "summary": "Deletes a pet", + "notes": "", + "type": null, + "nickname": "deletePet", + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, + "parameters": [ + { + "name": "petId", + "description": "Pet id to delete", + "required": true, + "type": "string", + "paramType": "path" + } + ] + } + ] + }, + { + "path": "/pet", + "operations": [ + { + "method": "PUT", + "summary": "Update an existing pet", + "notes": "", + "type": "void", + "nickname": "updatePet", + "authorizations": {}, + "parameters": [ + { + "name": "body", + "description": "Pet object that needs to be updated in the store", + "required": true, + "type": "Pet", + "paramType": "body" + } + ], + "responseMessages": [ + { + "code": 400, + "message": "Invalid ID supplied" + }, + { + "code": 404, + "message": "Pet not found" + }, + { + "code": 405, + "message": "Validation exception" + } + ] + }, + { + "method": "POST", + "summary": "Add a new pet to the store", + "notes": "", + "type": "void", + "nickname": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, + "parameters": [ + { + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "type": "Pet", + "paramType": "body" + } + ], + "responseMessages": [ + { + "code": 405, + "message": "Invalid input" + } + ] + } + ] + }, + { + "path": "/pet/findByStatus", + "operations": [ + { + "method": "GET", + "summary": "Finds Pets by status", + "notes": "Multiple status values can be provided with comma seperated strings", + "type": "array", + "items": { + "$ref": "Pet" + }, + "nickname": "findPetsByStatus", + "authorizations": {}, + "parameters": [ + { + "name": "status", + "description": "Status values that need to be considered for filter", + "defaultValue": "available", + "required": true, + "type": "string", + "paramType": "query", + "enum": [ + "available", + "pending", + "sold" + ] + } + ], + "responseMessages": [ + { + "code": 400, + "message": "Invalid status value" + } + ] + } + ] + }, + { + "path": "/pet/findByTags", + "operations": [ + { + "method": "GET", + "summary": "Finds Pets by tags", + "notes": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "type": "array", + "items": { + "$ref": "Pet" + }, + "nickname": "findPetsByTags", + "authorizations": {}, + "parameters": [ + { + "name": "tags", + "description": "Tags to filter by", + "required": true, + "type": "string", + "paramType": "query" + } + ], + "responseMessages": [ + { + "code": 400, + "message": "Invalid tag value" + } + ], + "deprecated": "true" + } + ] + }, + { + "path": "/pet/uploadImage", + "operations": [ + { + "method": "POST", + "summary": "uploads an image", + "notes": "", + "type": "void", + "nickname": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + }, + { + "scope": "test:nothing", + "description": "nothing" + } + ] + }, + "parameters": [ + { + "name": "additionalMetadata", + "description": "Additional data to pass to server", + "required": false, + "type": "string", + "paramType": "form" + }, + { + "name": "file", + "description": "file to upload", + "required": false, + "type": "File", + "paramType": "body" + } + ] + } + ] + } + ], + "models": { + "Tag": { + "id": "Tag", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Pet": { + "id": "Pet", + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64", + "description": "unique identifier for the pet", + "minimum": "0.0", + "maximum": "100.0" + }, + "category": { + "$ref": "Category" + }, + "name": { + "type": "string" + }, + "photoUrls": { + "type": "array", + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "items": { + "$ref": "Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + } + }, + "Category": { + "id": "Category", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + } +} \ No newline at end of file diff --git a/openapi-cli/src/test/resources/petstore_tags.yaml b/openapi-cli/src/test/resources/petstore_tags.yaml index 638d55e3f..a3dc9a379 100644 --- a/openapi-cli/src/test/resources/petstore_tags.yaml +++ b/openapi-cli/src/test/resources/petstore_tags.yaml @@ -48,7 +48,6 @@ paths: required: false schema: type: integer - format: int32 responses: '200': description: An paged array of pets diff --git a/openapi-cli/src/test/resources/petstore_type.yaml b/openapi-cli/src/test/resources/petstore_type.yaml index beab05df1..874080c36 100644 --- a/openapi-cli/src/test/resources/petstore_type.yaml +++ b/openapi-cli/src/test/resources/petstore_type.yaml @@ -71,7 +71,6 @@ components: properties: petId: type: integer - format: int32 name: type: string petType: diff --git a/openapi-cli/src/test/resources/petstore_wildcard.yaml b/openapi-cli/src/test/resources/petstore_wildcard.yaml new file mode 100644 index 000000000..9497bcfdc --- /dev/null +++ b/openapi-cli/src/test/resources/petstore_wildcard.yaml @@ -0,0 +1,92 @@ +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/my: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + description: "Request to add a pet" + content: + '*/*': + schema: + $ref: "#/components/schemas/Pets" + responses: + '200': + description: Successful operation + content: + '*/*': + schema: + type: array + items: + description: "Pet records" + + +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 + message: + type: string diff --git a/openapi-cli/src/test/resources/testng.xml b/openapi-cli/src/test/resources/testng.xml index 85adc2b03..da9a21e08 100644 --- a/openapi-cli/src/test/resources/testng.xml +++ b/openapi-cli/src/test/resources/testng.xml @@ -25,6 +25,7 @@ under the License. + @@ -42,6 +43,8 @@ under the License. + + @@ -54,6 +57,7 @@ under the License. + @@ -71,10 +75,12 @@ under the License. + + @@ -91,6 +97,11 @@ under the License. + + + + + diff --git a/openapi-client-idl-plugin/build.gradle b/openapi-client-idl-plugin/build.gradle new file mode 100644 index 000000000..bbca3ccd4 --- /dev/null +++ b/openapi-client-idl-plugin/build.gradle @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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. + */ + + +apply from: "$rootDir/gradle/javaProject.gradle" +apply plugin: "com.github.johnrengelman.shadow" +apply plugin: "java-library" + +description = "Ballerina - OpenAPI Tooling - OpenAPI to Ballerina" + +configurations.all { + resolutionStrategy.preferProjectModules() +} + +configurations { + balTools +} + +dependencies { + implementation project(':openapi-bal-service') + implementation project(':openapi-core') + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { + exclude group: "io.swagger", module: "swagger-compat-spec-parser" + exclude group: "org.slf4j", module: "slf4j-ext" + exclude group: "javax.validation", module: "validation-api" + } + implementation "io.swagger.core.v3:swagger-models" + implementation "javax.ws.rs:javax.ws.rs-api" + implementation "com.github.jknack:handlebars" + implementation "info.picocli:picocli" + implementation "org.ballerinalang:ballerina-lang" + implementation "org.ballerinalang:ballerina-parser" + implementation "org.ballerinalang:formatter-core" + implementation "org.ballerinalang:ballerina-cli" + implementation "org.ballerinalang:ballerina-tools-api" + implementation "io.ballerina.stdlib:http-native" + implementation "com.google.code.findbugs:jsr305" + testImplementation "org.testng:testng" + + balTools ("org.ballerinalang:jballerina-tools:${ballerinaLangVersion}") { + transitive = false + } +} + +def bDistribution = file("$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}") +task jBallerinaPack { + doLast { + configurations.balTools.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File(project.buildDir, "extracted-distribution/") + } + } + } + outputs.dir bDistribution +} + +task unpackStdLibs() { + dependsOn(jBallerinaPack) + doLast { + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File("${project.buildDir}/extracted-distribution/" + artifact.name + "-zip") + } + } + } +} + +task copyStdlibs(type: Copy) { + dependsOn(unpackStdLibs) + def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" + into ballerinaDist + + /* Standard Libraries */ + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + def artifactExtractedPath = "${project.buildDir}/extracted-distribution/" + artifact.name + "-zip" + into("repo/bala") { + from "${artifactExtractedPath}/bala/" + } + into("repo/cache") { + from "${artifactExtractedPath}/cache" + } + } +} + +test { + dependsOn { + copyStdlibs + } + systemProperty "ballerina.home", bDistribution + + useTestNG() { + suites "src/test/resources/testng.xml" + } +} + +shadowJar { + configurations = [project.configurations.runtimeClasspath] + dependencies { + include(dependency('com.github.jknack:handlebars')) + include(dependency('org.antlr:antlr4:4.5')) + include(dependency('io.swagger.parser.v3:swagger-parser')) + include(dependency('com.atlassian.commonmark:commonmark')) + include(dependency('com.atlassian.commonmark:commonmark-ext-gfm-tables')) + exclude('META-INF/*.SF') + exclude('META-INF/*.DSA') + exclude('META-INF/*.RSA') + } +} + +compileJava { + doFirst { + options.compilerArgs = [ + '--module-path', classpath.asPath, + ] + classpath = files() + } +} + diff --git a/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/Constants.java b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/Constants.java new file mode 100644 index 000000000..6c03687ad --- /dev/null +++ b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/Constants.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.idl.client; + +import io.ballerina.tools.diagnostics.DiagnosticSeverity; + +/** + * This class includes constants for client IDL generator. + * + * @since 1.3.0 + */ +public class Constants { + public static final String OPENAPI_CLIENT_REFERENCE = "openapi:ClientConfig"; + public static final String TAGS = "tags"; + public static final String OPERATIONS = "operations"; + public static final String NULLABLE = "nullable"; + public static final String IS_RESOURCE = "isResource"; + public static final String LICENSE = "license"; + public static final String TRUE = "true"; + public static final String MODULE_ALIAS = "openapi_client"; + public static final String OPENAPI_REGEX_PATTERN = "\"?(openapi|swagger)\"?\\s*:\\s*\"?[0-9]\\d*\\.\\d+\\.\\d+\"?"; + + /** + * Enum class for containing diagnostic messages. + */ + public enum DiagnosticMessages { + LICENSE_PATH_BLANK("OAS_IDL_CLIENT_01", "given license file path is an empty string.", + DiagnosticSeverity.WARNING), + ERROR_WHILE_READING_LICENSE_FILE("OAS_IDL_CLIENT_02", "unexpected error occurred while reading the license", + DiagnosticSeverity.ERROR), + ERROR_WHILE_GENERATING_CLIENT("OAS_IDL_CLIENT_03", "unexpected error occurred while generating the client", + DiagnosticSeverity.ERROR), + PARSER_ERROR("OAS_IDL_CLIENT_04", "", DiagnosticSeverity.ERROR); // parser errors are assigned directly to + // diagnostic via exceptions. + 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/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientGenerator.java b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientGenerator.java new file mode 100644 index 000000000..76b8437f6 --- /dev/null +++ b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientGenerator.java @@ -0,0 +1,451 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.idl.client; + +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.BasicLiteralNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.ListConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.ModuleClientDeclarationNode; +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.NodeLocation; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +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.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaClientGenerator; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.openapi.core.model.GenSrcFile; +import io.ballerina.projects.DocumentConfig; +import io.ballerina.projects.DocumentId; +import io.ballerina.projects.ModuleConfig; +import io.ballerina.projects.ModuleDescriptor; +import io.ballerina.projects.ModuleId; +import io.ballerina.projects.ModuleName; +import io.ballerina.projects.Package; +import io.ballerina.projects.plugins.IDLClientGenerator; +import io.ballerina.projects.plugins.IDLSourceGeneratorContext; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticFactory; +import io.ballerina.tools.diagnostics.DiagnosticInfo; +import io.ballerina.tools.diagnostics.Location; +import io.swagger.v3.oas.models.OpenAPI; +import org.ballerinalang.formatter.core.Formatter; +import org.ballerinalang.formatter.core.FormatterException; + +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.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.JSON_EXTENSION; +import static io.ballerina.openapi.core.GeneratorConstants.TYPE_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.UTIL_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.YAML_EXTENSION; +import static io.ballerina.openapi.core.GeneratorConstants.YML_EXTENSION; +import static io.ballerina.openapi.core.GeneratorUtils.normalizeOpenAPI; +import static io.ballerina.openapi.idl.client.Constants.IS_RESOURCE; +import static io.ballerina.openapi.idl.client.Constants.LICENSE; +import static io.ballerina.openapi.idl.client.Constants.NULLABLE; +import static io.ballerina.openapi.idl.client.Constants.OPENAPI_CLIENT_REFERENCE; +import static io.ballerina.openapi.idl.client.Constants.OPENAPI_REGEX_PATTERN; +import static io.ballerina.openapi.idl.client.Constants.OPERATIONS; +import static io.ballerina.openapi.idl.client.Constants.TAGS; +import static io.ballerina.openapi.idl.client.Constants.TRUE; + +/** + * The IDL plugin implementation for OpenAPI client generation. + * + * @since 1.3.0 + */ +public class OpenAPIClientGenerator extends IDLClientGenerator { + + @Override + public boolean canHandle(IDLSourceGeneratorContext idlSourceGeneratorContext) { + // check given contract is valid for the generating the client. + Path oasPath = idlSourceGeneratorContext.resourcePath(); + // resource with yaml, json extension + return isOpenAPI(oasPath, idlSourceGeneratorContext); + } + + @Override + public void perform(IDLSourceGeneratorContext idlSourceContext) { + + try { + List genSrcFiles = generateClientFiles(idlSourceContext); + if (genSrcFiles.isEmpty()) { + return; + } + String moduleName = getAlias(idlSourceContext.clientNode()); + ModuleId moduleId = ModuleId.create(moduleName, idlSourceContext.currentPackage().packageId()); + List documents = new ArrayList<>(); + + genSrcFiles.forEach(genSrcFile -> { + DocumentId documentId = DocumentId.create(genSrcFile.getFileName(), moduleId); + DocumentConfig documentConfig = DocumentConfig.from( + documentId, genSrcFile.getContent(), genSrcFile.getFileName()); + documents.add(documentConfig); + + }); + + ModuleDescriptor moduleDescriptor = ModuleDescriptor.from( + ModuleName.from(idlSourceContext.currentPackage().packageName(), moduleName), + idlSourceContext.currentPackage().descriptor()); + ModuleConfig moduleConfig = + ModuleConfig.from(moduleId, moduleDescriptor, documents, new ArrayList<>(), null, + new ArrayList<>()); + NodeList annotations = getAnnotationNodes(idlSourceContext); + //only pass openapi related annotation node. + List openapiAnnot = filterOpenAPIAnnotation(annotations); + + idlSourceContext.addClient(moduleConfig, openapiAnnot.isEmpty() ? NodeFactory.createEmptyNodeList() : + NodeFactory.createNodeList(openapiAnnot)); + } catch (BallerinaOpenApiException e) { + Constants.DiagnosticMessages error = Constants.DiagnosticMessages.PARSER_ERROR; + DiagnosticInfo diagnosticInfo = new DiagnosticInfo(error.getCode(), e.getMessage(), + error.getSeverity()); + Diagnostic diagnostic = DiagnosticFactory.createDiagnostic(diagnosticInfo, + idlSourceContext.clientNode().location()); + idlSourceContext.reportDiagnostic(diagnostic); + } catch (IOException | FormatterException e) { + Constants.DiagnosticMessages error = Constants.DiagnosticMessages.ERROR_WHILE_GENERATING_CLIENT; + reportDiagnostic(idlSourceContext, error, idlSourceContext.clientNode().location()); + } + } + + /** + * This method uses to check whether given specification can be handled via the openapi client generation tool. + * This includes basic requirements like file extension check and file header check. + */ + private static boolean isOpenAPI(Path oasPath, IDLSourceGeneratorContext context) { + + try { + if (!(oasPath.toString().endsWith(YAML_EXTENSION) || oasPath.toString().endsWith(JSON_EXTENSION) || + oasPath.toString().endsWith(YML_EXTENSION))) { + return false; + } + String content = Files.readString(oasPath); + Pattern openapiPattern = Pattern.compile(OPENAPI_REGEX_PATTERN); + Matcher openapiMatcher = openapiPattern.matcher(content); + return openapiMatcher.find(); + } catch (IOException | NullPointerException e) { + return false; + } + } + + /** + * This function uses to filter @openapi:ClientConfig annotation from given annotation list. + */ + private static List filterOpenAPIAnnotation(NodeList annotations) { + + List openapiAnnot = new ArrayList<>(); + for (AnnotationNode annotationNode : annotations) { + Node refNode = annotationNode.annotReference(); + boolean isNodeExist = refNode.toString().trim().equals(OPENAPI_CLIENT_REFERENCE); + if (!isNodeExist) { + continue; + } + openapiAnnot.add(annotationNode); + } + return openapiAnnot; + } + + private static NodeList getAnnotationNodes(IDLSourceGeneratorContext idlSourceContext) { + + ModuleClientDeclarationNode clientNode = idlSourceContext.clientNode(); + NodeList annotations = clientNode.annotations(); + return annotations; + } + + /** + * This method uses to generate ballerina files for openapi client stub. + * This will return list of (client.bal, util.bal, types.bal) {@code GenSrcFile}. + */ + private List generateClientFiles(IDLSourceGeneratorContext context) + throws IOException, BallerinaOpenApiException, FormatterException { + + Path openAPI = context.resourcePath(); + + // extract annotation details + ModuleClientDeclarationNode clientNode = context.clientNode(); + NodeList annotations = clientNode.annotations(); + OASClientConfig oasClientConfig = extractClientDetails(context, openAPI, annotations); + + + List sourceFiles = new ArrayList<>(); + + // generate ballerina client files. + String licenseContent = oasClientConfig.getLicense(); + BallerinaClientGenerator ballerinaClientGenerator = new BallerinaClientGenerator(oasClientConfig); + String mainContent = Formatter.format(ballerinaClientGenerator.generateSyntaxTree()).toString(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, null, CLIENT_FILE_NAME, + licenseContent == null || licenseContent.isBlank() ? mainContent : + licenseContent + System.lineSeparator() + mainContent)); + String utilContent = Formatter.format( + ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree()).toString(); + + if (!utilContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.UTIL_SRC, null, UTIL_FILE_NAME, + licenseContent == null || licenseContent.isBlank() ? utilContent : + licenseContent + System.lineSeparator() + utilContent)); + } + + // generate ballerina records to represent schemas. + List typeDefinitionNodeList = new LinkedList<>(); + typeDefinitionNodeList.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList()); + typeDefinitionNodeList.addAll(ballerinaClientGenerator + .getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(oasClientConfig.getOpenAPI(), + oasClientConfig.isNullable(), typeDefinitionNodeList); + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + String schemaContent = Formatter.format(schemaSyntaxTree).toString(); + + if (oasClientConfig.getFilters().getTags().size() > 0) { + // remove unused records and enums when generating the client by the tags given. + schemaContent = GeneratorUtils.removeUnusedEntities(schemaSyntaxTree, mainContent, schemaContent, + null); + } + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, null, TYPE_FILE_NAME, + licenseContent == null || licenseContent.isBlank() ? schemaContent : + licenseContent + System.lineSeparator() + schemaContent)); + } + + return sourceFiles; + } + + /** + * This method extracts openapi client config details. + * ex: openapi annotation + *
+     * public type ClientConfig record {|
+     *     string[]? tags = [];
+     *     string[]? operations = [];
+     *     boolean nullable = true;
+     *     boolean isResource = true;
+     *     string license?;
+     * |};
+     * 
+ * + * @param annotations - Client node annotation list + * @return {@code ClientMetaData} model with all the metadata to generate client. + */ + private static OASClientConfig extractClientDetails(IDLSourceGeneratorContext context, Path openAPI, + NodeList annotations) + throws IOException, BallerinaOpenApiException { + + OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder(); + clientMetaDataBuilder.withPlugin(true); + Filter filter = new Filter(); + if (annotations == null) { + // normalize OpenAPI definition. + OpenAPI openAPIDef = normalizeOpenAPI(openAPI, false); + clientMetaDataBuilder.withOpenAPI(openAPIDef); + return clientMetaDataBuilder.build(); + } + boolean isResources = true; + for (AnnotationNode annotationNode : annotations) { + Node refNode = annotationNode.annotReference(); + boolean isNodeExist = refNode.toString().trim().equals(OPENAPI_CLIENT_REFERENCE); + if (!isNodeExist) { + continue; + } + Optional annotFields = annotationNode.annotValue(); + if (annotFields.isEmpty()) { + continue; + } + for (MappingFieldNode field : annotFields.get().fields()) { + if (!(field instanceof SpecificFieldNode)) { + continue; + } + SpecificFieldNode specificField = (SpecificFieldNode) field; + Optional expressionNode = specificField.valueExpr(); + if (expressionNode.isEmpty()) { + continue; + } + ExpressionNode expression = expressionNode.get(); + ListConstructorExpressionNode list; + List values = new ArrayList<>(); + if (expression instanceof ListConstructorExpressionNode) { + list = (ListConstructorExpressionNode) expression; + values = extractListValues(list); + } + Node fieldName = specificField.fieldName(); + String attributeName = ((Token) fieldName).text(); + switch (attributeName) { + case TAGS: + filter.setTags(values); + break; + case OPERATIONS: + filter.setOperations(values); + break; + case NULLABLE: + clientMetaDataBuilder.withNullable(expression.toString().contains(TRUE)); + break; + case IS_RESOURCE: + isResources = expression.toString().contains(TRUE); + clientMetaDataBuilder.withResourceMode(isResources); + break; + case LICENSE: + clientMetaDataBuilder.withLicense( + expression.kind() == SyntaxKind.STRING_LITERAL && !expression.toString().isBlank() ? + getLicenseContent(context, + Paths.get(getStringValue((BasicLiteralNode) expression))) : ""); + break; + default: + break; + } + } + } + // normalize OpenAPI definition. + clientMetaDataBuilder.withFilters(filter); + OpenAPI openAPIDef = normalizeOpenAPI(openAPI, !isResources); + clientMetaDataBuilder.withOpenAPI(openAPIDef); + + return clientMetaDataBuilder.build(); + } + + /** + * This util is for extracting the list value from annotation field. + */ + private static List extractListValues(ListConstructorExpressionNode list) { + + SeparatedNodeList expressions = list.expressions(); + Iterator iterator = expressions.iterator(); + List values = new ArrayList<>(); + while (iterator.hasNext()) { + Node item = iterator.next(); + if (item.kind() == SyntaxKind.STRING_LITERAL && !item.toString().isBlank()) { + String text = getStringValue((BasicLiteralNode) item); + values.add(text); + } + } + return values; + } + + /** + * Util to normalize the string value by removing extra " " from given field value. + */ + private static String getStringValue(BasicLiteralNode item) { + + Token stringItem = item.literalToken(); + String text = stringItem.text(); + // here we need to do some preprocessing by removing '"' from the given values. + if (text.length() > 1 && text.charAt(0) == '"' && text.charAt(text.length() - 1) == '"') { + text = text.substring(1, text.length() - 1); + } else { + // missing end quote case + text = text.substring(1); + } + return text; + } + + /** + * Util to read license content. + */ + private static String getLicenseContent(IDLSourceGeneratorContext context, Path licensePath) { + + Path relativePath = null; + String licenseHeader = ""; + NodeLocation location = context.clientNode().location(); + Path ballerinaFilePath = extractBallerinaFilePath(context); + if (ballerinaFilePath == null) { + return null; + } + try { + if (licensePath.toString().isBlank()) { + Constants.DiagnosticMessages error = Constants.DiagnosticMessages.LICENSE_PATH_BLANK; + reportDiagnostic(context, error, location); + } else { + Path finalLicensePath = Paths.get(licensePath.toString()); + if (finalLicensePath.isAbsolute()) { + relativePath = finalLicensePath; + } else { + File file = new File(ballerinaFilePath.toString()); + File parentFolder = new File(file.getParent()); + File openapiContract = new File(parentFolder, licensePath.toString()); + relativePath = Paths.get(openapiContract.getCanonicalPath()); + } + } + if (relativePath != null) { + try { + String newLine = System.lineSeparator(); + Path filePath = Paths.get((new File(relativePath.toString()).getCanonicalPath())); + licenseHeader = Files.readString(Paths.get(filePath.toString())); + if (!licenseHeader.endsWith(newLine)) { + licenseHeader = licenseHeader + newLine + newLine; + } else if (!licenseHeader.endsWith(newLine + newLine)) { + licenseHeader = licenseHeader + newLine; + } + } catch (IOException e) { + Constants.DiagnosticMessages error = Constants.DiagnosticMessages + .ERROR_WHILE_READING_LICENSE_FILE; + reportDiagnostic(context, error, location); + return null; + } + return licenseHeader; + } + } catch (IOException e) { + Constants.DiagnosticMessages error = Constants.DiagnosticMessages.ERROR_WHILE_READING_LICENSE_FILE; + reportDiagnostic(context, error, location); + return null; + } + return licenseHeader; + } + + private static void reportDiagnostic(IDLSourceGeneratorContext context, Constants.DiagnosticMessages error, + Location location) { + + DiagnosticInfo diagnosticInfo = new DiagnosticInfo(error.getCode(), error.getDescription(), + error.getSeverity()); + Diagnostic diagnostic = DiagnosticFactory.createDiagnostic(diagnosticInfo, location); + context.reportDiagnostic(diagnostic); + } + + private static Path extractBallerinaFilePath(IDLSourceGeneratorContext idlSourceContext) { + + Package aPackage = idlSourceContext.currentPackage(); + DocumentId packageDoc = aPackage.getDefaultModule().documentIds().stream().findFirst().get(); + Optional path = aPackage.project().documentPath(packageDoc); + return path.orElse(null); + } + + private String getAlias(ModuleClientDeclarationNode clientNode) { + return clientNode.clientPrefix().text(); + } +} diff --git a/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientIDLPlugin.java b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientIDLPlugin.java new file mode 100644 index 000000000..8672a2ddc --- /dev/null +++ b/openapi-client-idl-plugin/src/main/java/io/ballerina/openapi/idl/client/OpenAPIClientIDLPlugin.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.idl.client; + +import io.ballerina.projects.plugins.IDLGeneratorPlugin; +import io.ballerina.projects.plugins.IDLPluginContext; + +/** + * The IDL plugin implementation for OpeAPI client generation . + * + * @since 1.3.0 + */ +public class OpenAPIClientIDLPlugin extends IDLGeneratorPlugin { + + @Override + public void init(IDLPluginContext idlPluginContext) { + idlPluginContext.addCodeGenerator(new OpenAPIClientGenerator()); + } +} diff --git a/openapi-client-idl-plugin/src/main/java/module-info.java b/openapi-client-idl-plugin/src/main/java/module-info.java new file mode 100644 index 000000000..922a997c2 --- /dev/null +++ b/openapi-client-idl-plugin/src/main/java/module-info.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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. + */ + +module io.ballerina.openapi.idl.client { + requires io.ballerina.lang; + requires io.ballerina.parser; + requires io.ballerina.stdlib.http; + requires io.ballerina.tools.api; + requires io.ballerina.formatter.core; + requires io.ballerina.openapi.converter; + requires io.swagger.v3.core; + requires io.swagger.v3.oas.models; + requires java.ws.rs; + requires jsr305; + requires org.apache.commons.io; + requires org.slf4j; + requires org.apache.commons.lang3; + requires io.ballerina.openapi.core; +} diff --git a/openapi-client-idl-plugin/src/main/resources/META-INF/services/io.ballerina.projects.plugins.IDLGeneratorPlugin b/openapi-client-idl-plugin/src/main/resources/META-INF/services/io.ballerina.projects.plugins.IDLGeneratorPlugin new file mode 100644 index 000000000..7890aee89 --- /dev/null +++ b/openapi-client-idl-plugin/src/main/resources/META-INF/services/io.ballerina.projects.plugins.IDLGeneratorPlugin @@ -0,0 +1 @@ +io.ballerina.openapi.idl.client.OpenAPIClientIDLPlugin diff --git a/openapi-core/build.gradle b/openapi-core/build.gradle new file mode 100644 index 000000000..c3961fd5f --- /dev/null +++ b/openapi-core/build.gradle @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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. + */ + +apply from: "$rootDir/gradle/javaProject.gradle" +apply plugin: "com.github.johnrengelman.shadow" +apply plugin: "java-library" + +description = "Ballerina - OpenAPI Tooling - OpenAPI to Ballerina" + +configurations.all { + resolutionStrategy.preferProjectModules() +} + +configurations { + balTools +} + +dependencies { + implementation project(':openapi-bal-service') + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { + exclude group: "io.swagger", module: "swagger-compat-spec-parser" + exclude group: "org.slf4j", module: "slf4j-ext" + exclude group: "javax.validation", module: "validation-api" + } + implementation "io.swagger.core.v3:swagger-models" + implementation "javax.ws.rs:javax.ws.rs-api" + implementation "com.github.jknack:handlebars" + implementation "info.picocli:picocli" + implementation "org.ballerinalang:ballerina-lang" + implementation "org.ballerinalang:ballerina-parser" + implementation "org.ballerinalang:formatter-core" + implementation "org.ballerinalang:ballerina-cli" + implementation "org.ballerinalang:ballerina-tools-api" + implementation "org.ballerinalang:ballerina-runtime" + implementation "io.ballerina.stdlib:http-native" + implementation "com.google.code.findbugs:jsr305" + testImplementation "org.testng:testng" + + balTools ("org.ballerinalang:jballerina-tools:${ballerinaLangVersion}") { + transitive = false + } +} + +def bDistribution = file("$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}") +task jBallerinaPack { + doLast { + configurations.balTools.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File(project.buildDir, "extracted-distribution/") + } + } + } + outputs.dir bDistribution +} + +task unpackStdLibs() { + dependsOn(jBallerinaPack) + doLast { + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File("${project.buildDir}/extracted-distribution/" + artifact.name + "-zip") + } + } + } +} + +task copyStdlibs(type: Copy) { + dependsOn(unpackStdLibs) + def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" + into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + + /* Standard Libraries */ + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + def artifactExtractedPath = "${project.buildDir}/extracted-distribution/" + artifact.name + "-zip" + into("repo/bala") { + from "${artifactExtractedPath}/bala/" + } + into("repo/cache") { + from "${artifactExtractedPath}/cache" + } + } +} + +test { + dependsOn { + copyStdlibs + } + systemProperty "ballerina.home", bDistribution + + useTestNG() { + suites "src/test/resources/testng.xml" + } +} + +shadowJar { + configurations = [project.configurations.runtimeClasspath] + dependencies { + include(dependency('com.github.jknack:handlebars')) + include(dependency('org.antlr:antlr4:4.5')) + include(dependency('io.swagger.parser.v3:swagger-parser:2.1.15')) + include(dependency('com.atlassian.commonmark:commonmark')) + include(dependency('com.atlassian.commonmark:commonmark-ext-gfm-tables')) + exclude('META-INF/*.SF') + exclude('META-INF/*.DSA') + exclude('META-INF/*.RSA') + } +} + +compileJava { + doFirst { + options.compilerArgs = [ + '--module-path', classpath.asPath, + ] + classpath = files() + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/ErrorMessages.java b/openapi-core/src/main/java/io/ballerina/openapi/core/ErrorMessages.java new file mode 100644 index 000000000..64312f8aa --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/ErrorMessages.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core; + +/** + * Container for error messages of the OpenAPI command. + * + * @since 1.3.0 + */ +public class ErrorMessages { + + public static String invalidFilePath(String path) { + return String.format("OpenAPI 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."; + } + + public static String invalidPathParamType(String parameterName) { + return String.format("Invalid path parameter data type for the parameter: '%s'", parameterName); + } + + public static String unsupportedOpenAPIVersion() { + return "Provided OpenAPI contract version is not supported in the tool. " + + "Use OpenAPI specification version 2 or higher"; + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorConstants.java b/openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorConstants.java similarity index 69% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorConstants.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorConstants.java index 2bf299987..045141ffa 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/GeneratorConstants.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorConstants.java @@ -1,29 +1,32 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators; +package io.ballerina.openapi.core; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; /** * Constants for openapi code generator. + * + * @since 1.3.0 */ public class GeneratorConstants { @@ -39,13 +42,11 @@ public enum GenType { private String name; GenType(String name) { - this.name = name; } @Override public String toString() { - return this.name; } } @@ -66,12 +67,10 @@ public enum AuthConfigTypes { private final String authType; AuthConfigTypes(String authType) { - this.authType = authType; } public String getValue() { - return authType; } } @@ -88,16 +87,12 @@ public String getValue() { "name= \"testopenapi\"\n" + "version= \"0.0.0\"\n"; - public static final String TEMPLATES_SUFFIX = ".mustache"; - public static final String TEMPLATES_DIR_PATH_KEY = "templates.dir.path"; - public static final String DEFAULT_TEMPLATE_DIR = "/templates"; - public static final String DEFAULT_CLIENT_DIR = DEFAULT_TEMPLATE_DIR + "/client"; - public static final String DEFAULT_CLIENT_PKG = "client"; - public static final String DEFAULT_MOCK_PKG = "mock"; public static final String OAS_PATH_SEPARATOR = "/"; - public static final String USER_DIR = "user.dir"; - public static final String UNTITLED_SERVICE = "UntitledAPI"; - public static final String ESCAPE_PATTERN = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/\\_{}\\s|.$])"; + public static final String ESCAPE_PATTERN = "([\\[\\]\\\\?!<>@#&~'`*\\-=^+();:\\/{}\\s|.$])"; + public static final String REGEX_WITHOUT_SPECIAL_CHARACTERS = "\\b[_a-zA-Z][_a-zA-Z0-9]*\\b"; + public static final String REGEX_WORDS_STARTING_WITH_NUMBERS = "^[0-9].*"; + public static final String REGEX_ONLY_NUMBERS_OR_NUMBERS_WITH_SPECIAL_CHARACTERS = "\\b[0-9([\\[\\]\\\\?!<>@#&~'`" + + "*\\-=^+();:\\/{}\\s|.$])]*\\b"; //ClientCode generator public static final String HTTP = "http"; public static final String URL = "url"; @@ -125,6 +120,8 @@ public String getValue() { public static final String HEADER_VALUES = "headerValues"; public static final String PAYLOAD = "payload"; public static final String PAYLOAD_KEYWORD = "Payload"; + public static final String REQUEST = "request"; + public static final String HTTP_REQUEST = "http:Request"; public static final String PDF = "pdf"; public static final String QUERY_PARAM = "queryParam"; public static final String SELF = "self"; @@ -148,26 +145,41 @@ public String getValue() { public static final String APPLICATION_URL_ENCODE = "application/x-www-form-urlencoded"; public static final String TEXT = "text"; public static final String IMAGE_PNG = "image/png"; - public static final String TEXT_PLAIN = "text/plain"; + public static final String ENSURE_TYPE = "ensureType"; // auth related constants public static final String API_KEY = "apikey"; public static final String API_KEYS_CONFIG = "ApiKeysConfig"; public static final String API_KEY_CONFIG_PARAM = "apiKeyConfig"; - public static final String API_KEY_CONFIG_RECORD_FIELD = "apiKeys"; public static final String AUTH = "auth"; public static final String AUTH_CONFIG = "authConfig"; - public static final String AUTH_CONFIG_RECORD = "AuthConfig"; + public static final String HTTP_CLIENT_CONFIG = "httpClientConfig"; + public static final String CLIENT_HTTP1_SETTINGS = "ClientHttp1Settings"; + public static final String CLIENT_HTTP1_SETTINGS_FIELD = "http1Settings"; + public static final String HTTP2_SETTINGS = "http:ClientHttp2Settings"; + public static final String HTTP2_SETTINGS_FIELD = "http2Settings"; + public static final String SETTINGS = "settings"; + public static final String CACHE_CONFIG = "http:CacheConfig"; + public static final String CACHE_CONFIG_FIELD = "cache"; + public static final String RESPONSE_LIMIT = "http:ResponseLimitConfigs"; + public static final String RESPONSE_LIMIT_FIELD = "responseLimits"; + public static final String SECURE_SOCKET = "http:ClientSecureSocket"; + public static final String SECURE_SOCKET_FIELD = "secureSocket"; + public static final String PROXY = "http:ProxyConfig"; + + public static final String KEEP_ALIVE = "keepAlive"; + public static final String CHUNKING = "chunking"; 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 CONFIG_RECORD_ARG = "clientConfig"; - public static final String CLIENT_CONFIG = "ClientConfig"; + public static final String CONNECTION_CONFIG = "ConnectionConfig"; public static final String OAUTH2 = "oauth2"; public static final String SSL_FIELD_NAME = "secureSocket"; public static final String PROXY_CONFIG = "proxy"; + public static final String VALIDATION = "validation"; + public static final String DEFAULT_API_KEY_DESC = "API keys for authorization"; public static final String RESPONSE = "response"; @@ -182,10 +194,7 @@ public String getValue() { public static final String PATCH = "patch"; public static final String EXECUTE = "execute"; public static final String HEAD = "head"; - public static final String CONNECT = "connect"; public static final String OPTIONS = "options"; - public static final String TRACE = "trace"; - //Encoding related constants public static final String DEEP_OBJECT = "DEEPOBJECT"; public static final String FORM = "FORM"; @@ -200,6 +209,7 @@ public String getValue() { public static final String X_BALLERINA_INIT_DESCRIPTION = "x-ballerina-init-description"; public static final String X_BALLERINA_DISPLAY = "x-ballerina-display"; public static final String X_BALLERINA_DEPRECATED_REASON = "x-ballerina-deprecated-reason"; + public static final String X_BALLERINA_HTTP_CONFIGURATIONS = "x-ballerina-http-configurations"; //Service related public static final String HOST = "host"; @@ -209,7 +219,7 @@ public String getValue() { public static final String HTTP_RESPONSE = "http:Response"; public static final String DEFAULT = "default"; /** - * Util for select http key words with http codes. + * Util for select http keywords with http codes. * * @param code http code. * @return Http identification word. @@ -220,6 +230,8 @@ public String getValue() { Map httpCodeMap = new HashMap<>(); httpCodeMap.put("100", "Continue"); httpCodeMap.put("101", "SwitchingProtocols"); + httpCodeMap.put("102", "Processing"); + httpCodeMap.put("103", "EarlyHints"); httpCodeMap.put("200", "Ok"); httpCodeMap.put("201", "Created"); httpCodeMap.put("202", "Accepted"); @@ -227,6 +239,9 @@ public String getValue() { httpCodeMap.put("204", "NoContent"); httpCodeMap.put("205", "RestContent"); httpCodeMap.put("206", "PartialContent"); + httpCodeMap.put("207", "MultiStatus"); + httpCodeMap.put("208", "AlreadyReported"); + httpCodeMap.put("226", "IMUsed"); httpCodeMap.put("300", "MultipleChoices"); httpCodeMap.put("301", "MovedPermanently"); httpCodeMap.put("302", "Found"); @@ -253,19 +268,32 @@ public String getValue() { httpCodeMap.put("415", "UnsupportedMediaType"); httpCodeMap.put("416", "RangeNotSatisfiable"); httpCodeMap.put("417", "ExpectationFailed"); + httpCodeMap.put("421", "MisdirectedRequest"); + httpCodeMap.put("422", "UnprocessableEntity"); + httpCodeMap.put("423", "Locked"); + httpCodeMap.put("424", "FailedDependency"); + httpCodeMap.put("425", "TooEarly"); httpCodeMap.put("426", "UpgradeRequired"); + httpCodeMap.put("428", "PreconditionRequired"); httpCodeMap.put("429", "TooManyRequests"); httpCodeMap.put("431", "RequestHeaderFieldsTooLarge"); + httpCodeMap.put("451", "UnavailableDueToLegalReasons"); httpCodeMap.put("500", "InternalServerError"); httpCodeMap.put("501", "NotImplemented"); httpCodeMap.put("502", "BadGateway"); httpCodeMap.put("503", "ServiceUnavailable"); - httpCodeMap.put("504", "GatewayTimeOut"); + httpCodeMap.put("504", "GatewayTimeout"); httpCodeMap.put("505", "HttpVersionNotSupported"); + httpCodeMap.put("506", "VariantAlsoNegotiates"); + httpCodeMap.put("507", "InsufficientStorage"); + httpCodeMap.put("508", "LoopDetected"); + httpCodeMap.put("510", "NotExtended"); + httpCodeMap.put("511", "NetworkAuthenticationRequired"); HTTP_CODES_DES = Collections.unmodifiableMap(httpCodeMap); } public static final String HTTP_200 = "200"; + public static final String HTTP_201 = "201"; public static final String INTEGER = "integer"; public static final String BOOLEAN = "boolean"; public static final String NUMBER = "number"; @@ -273,14 +301,20 @@ public String getValue() { public static final Integer MAX_ARRAY_LENGTH = 2147483637; public static final String NILLABLE = "?"; public static final String SQUARE_BRACKETS = "[]"; - public static final String BAL_EXTENSION = ".bal"; - public static final String JSON_EXTENSION = ".json"; - public static final String YAML_EXTENSION = ".yaml"; - public static final String YML_EXTENSION = ".yml"; - public static final Map TYPE_MAP; + public static final Map> OPENAPI_TYPE_TO_FORMAT_MAP; + public static final Map OPENAPI_TYPE_TO_BAL_TYPE_MAP; static { + // Add values to `OPENAPI_TYPE_TO_FORMAT_MAP` + Map> typeToFormatMap = new HashMap<>(); + typeToFormatMap.put("integer", List.of("int32", "int64")); + typeToFormatMap.put("number", List.of("float", "double")); + typeToFormatMap.put("string", List.of("date", "date-time", "password", "byte", "binary")); + OPENAPI_TYPE_TO_FORMAT_MAP = Collections.unmodifiableMap(typeToFormatMap); + + // Add values to `OPENAPI_TYPE_TO_BAL_TYPE_MAP`, + // ***Note: If any new format is added, Please check the constraint support also.*** Map typeMap = new HashMap<>(); typeMap.put("integer", "int"); typeMap.put("string", "string"); @@ -293,7 +327,20 @@ public String getValue() { typeMap.put("float", "float"); typeMap.put("binary", "byte[]"); typeMap.put("byte", "byte[]"); - TYPE_MAP = Collections.unmodifiableMap(typeMap); + typeMap.put("int32", "int:Signed32"); + typeMap.put("int64", "int"); + OPENAPI_TYPE_TO_BAL_TYPE_MAP = Collections.unmodifiableMap(typeMap); + } + + public static final String DEFAULT_HTTP_VERSION = "2.0"; + public static final Map HTTP_VERSION_MAP; + + static { + Map httpVersionMap = new HashMap<>(); + httpVersionMap.put("1.0", "http:HTTP_1_0"); + httpVersionMap.put("1.1", "http:HTTP_1_1"); + httpVersionMap.put("2.0", "http:HTTP_2_0"); + HTTP_VERSION_MAP = Collections.unmodifiableMap(httpVersionMap); } //Error related @@ -316,6 +363,7 @@ public String getValue() { public static final String OPEN_CURLY_BRACE = "{"; public static final String CLOSE_CURLY_BRACE = "}"; public static final String SLASH = "/"; + public static final String CATCH_ALL_PATH = "/*"; public static final String CONSTRAINT = "constraint"; public static final String CONSTRAINT_STRING = "constraint:String"; @@ -334,4 +382,29 @@ public String getValue() { 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 HTTP_VERSION = "http:HttpVersion"; + public static final String YAML_EXTENSION = ".yaml"; + public static final String YML_EXTENSION = ".yml"; + public static final String JSON_EXTENSION = ".json"; + public static final String UNSUPPORTED_OPENAPI_VERSION_PARSER_MESSAGE = "attribute swaggerVersion is unexpected"; + public static final String PIPE = "|"; + public static final String RETURNS = "returns"; + public static final String ANYDATA = "anydata"; + public static final String RESPONSE_RECORD_NAME = "Response"; + public static final String HTTP_VERIONS_EXT = "httpVersion"; + public static final String SERVICE_TYPE_NAME = "OASServiceType"; + public static final String DEFAULT_RETURN_COMMENT = "return value description"; + public static final String DEFAULT_FUNC_COMMENT = "Description"; + public static final String DEFAULT_PARAM_COMMENT = "parameter description"; + public static final String EMPTY_RECORD = "record{}"; + public static final String DO_NOT_MODIFY_FILE_HEADER = "// AUTO-GENERATED FILE. DO NOT MODIFY.\n" + + "// This file is auto-generated by the Ballerina OpenAPI tool.\n\n"; + public static final String DEFAULT_FILE_HEADER = "// AUTO-GENERATED FILE.\n" + + "// This file is auto-generated by the Ballerina OpenAPI tool.\n\n"; + public static final String HTTP_CALLER = "http:Caller"; + public static final String CALLER = "caller"; + public static final String NULL = "null"; + public static final String INT = "int"; + public static final String INT_SIGNED32 = "int:Signed32"; + public static final String DECIMAL = "decimal"; } diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorUtils.java b/openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorUtils.java new file mode 100644 index 000000000..3dcaee768 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/GeneratorUtils.java @@ -0,0 +1,1105 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core; + +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.api.symbols.SymbolKind; +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.ChildNodeEntry; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +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.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.Minutiae; +import io.ballerina.compiler.syntax.tree.MinutiaeList; +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.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.RecordFieldNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +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.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxInfo; +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.TypedBindingPatternNode; +import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.BallerinaUtilGenerator; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.EnumGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.model.GenSrcFile; +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.Location; +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.servers.ServerVariable; +import io.swagger.v3.oas.models.servers.ServerVariables; +import io.swagger.v3.parser.core.models.ParseOptions; +import io.swagger.v3.parser.core.models.SwaggerParseResult; +import org.apache.commons.io.FileUtils; +import org.ballerinalang.formatter.core.Formatter; +import org.ballerinalang.formatter.core.FormatterException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.ws.rs.core.MediaType; + +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.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.createCaptureBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createResourcePathParameterNode; +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.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_BRACKET_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.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACKET_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SLASH_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_KEYWORD; +import static io.ballerina.openapi.core.GeneratorConstants.ARRAY; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA_TOML; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA_TOML_CONTENT; +import static io.ballerina.openapi.core.GeneratorConstants.BOOLEAN; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.CLOSE_CURLY_BRACE; +import static io.ballerina.openapi.core.GeneratorConstants.CONSTRAINT; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_PARAM_COMMENT; +import static io.ballerina.openapi.core.GeneratorConstants.EXPLODE; +import static io.ballerina.openapi.core.GeneratorConstants.GET; +import static io.ballerina.openapi.core.GeneratorConstants.HEAD; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_RESPONSE; +import static io.ballerina.openapi.core.GeneratorConstants.IDENTIFIER; +import static io.ballerina.openapi.core.GeneratorConstants.IMAGE_PNG; +import static io.ballerina.openapi.core.GeneratorConstants.INTEGER; +import static io.ballerina.openapi.core.GeneratorConstants.JSON_EXTENSION; +import static io.ballerina.openapi.core.GeneratorConstants.LINE_SEPARATOR; +import static io.ballerina.openapi.core.GeneratorConstants.NILLABLE; +import static io.ballerina.openapi.core.GeneratorConstants.NULL; +import static io.ballerina.openapi.core.GeneratorConstants.NUMBER; +import static io.ballerina.openapi.core.GeneratorConstants.OBJECT; +import static io.ballerina.openapi.core.GeneratorConstants.OPEN_CURLY_BRACE; +import static io.ballerina.openapi.core.GeneratorConstants.REGEX_ONLY_NUMBERS_OR_NUMBERS_WITH_SPECIAL_CHARACTERS; +import static io.ballerina.openapi.core.GeneratorConstants.REGEX_WITHOUT_SPECIAL_CHARACTERS; +import static io.ballerina.openapi.core.GeneratorConstants.REGEX_WORDS_STARTING_WITH_NUMBERS; +import static io.ballerina.openapi.core.GeneratorConstants.SERVICE_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.SLASH; +import static io.ballerina.openapi.core.GeneratorConstants.SPECIAL_CHARACTERS_REGEX; +import static io.ballerina.openapi.core.GeneratorConstants.SQUARE_BRACKETS; +import static io.ballerina.openapi.core.GeneratorConstants.STRING; +import static io.ballerina.openapi.core.GeneratorConstants.STYLE; +import static io.ballerina.openapi.core.GeneratorConstants.TYPE_FILE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.OPENAPI_TYPE_TO_FORMAT_MAP; +import static io.ballerina.openapi.core.GeneratorConstants.TYPE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.UNSUPPORTED_OPENAPI_VERSION_PARSER_MESSAGE; +import static io.ballerina.openapi.core.GeneratorConstants.YAML_EXTENSION; +import static io.ballerina.openapi.core.GeneratorConstants.YML_EXTENSION; + +/** + * This class util for store all the common scenarios. + * + * @since 1.3.0 + */ +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(); + private static final Logger LOGGER = LoggerFactory.getLogger(BallerinaUtilGenerator.class); + private static final PrintStream OUT_STREAM = System.err; + + private static final List primitiveTypeList = + new ArrayList<>(Arrays.asList(GeneratorConstants.INTEGER, GeneratorConstants.NUMBER, + GeneratorConstants.STRING, GeneratorConstants.BOOLEAN)); + + 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); + } + + public static QualifiedNameReferenceNode getQualifiedNameReferenceNode(String modulePrefix, String identifier) { + Token modulePrefixToken = AbstractNodeFactory.createIdentifierToken(modulePrefix); + Token colon = AbstractNodeFactory.createIdentifierToken(":"); + IdentifierToken identifierToken = AbstractNodeFactory.createIdentifierToken(identifier); + return NodeFactory.createQualifiedNameReferenceNode(modulePrefixToken, colon, identifierToken); + } + + /** + * Generated resource function relative path node list. + * + * @param path - resource path + * @param operation - resource operation + * @return - node lists + * @throws BallerinaOpenApiException + */ + public static List getRelativeResourcePath(String path, Operation operation, List resourceFunctionDocs) + throws BallerinaOpenApiException { + + List functionRelativeResourcePath = new ArrayList<>(); + String[] pathNodes = path.split(SLASH); + if (pathNodes.length >= 2) { + for (String pathNode : pathNodes) { + if (pathNode.contains(OPEN_CURLY_BRACE)) { + String pathParam = pathNode; + pathParam = pathParam.substring(pathParam.indexOf(OPEN_CURLY_BRACE) + 1); + pathParam = pathParam.substring(0, pathParam.indexOf(CLOSE_CURLY_BRACE)); + pathParam = getValidName(pathParam, false); + + /** + * TODO -> `onCall/[string id]\.json` type of url won't support from syntax + * issue https://github.com/ballerina-platform/ballerina-spec/issues/1138 + *
resource function get onCall/[string id]\.json() returns string {}
+                     */
+                    if (operation.getParameters() != null) {
+                        extractPathParameterDetails(operation, functionRelativeResourcePath, pathNode,
+                                pathParam, resourceFunctionDocs);
+                    }
+                } else if (!pathNode.isBlank()) {
+                    IdentifierToken idToken = createIdentifierToken(escapeIdentifier(pathNode.trim()));
+                    functionRelativeResourcePath.add(idToken);
+                    functionRelativeResourcePath.add(createToken(SLASH_TOKEN));
+                }
+            }
+            functionRelativeResourcePath.remove(functionRelativeResourcePath.size() - 1);
+        } else if (pathNodes.length == 0) {
+            IdentifierToken idToken = createIdentifierToken(".");
+            functionRelativeResourcePath.add(idToken);
+        } else {
+            IdentifierToken idToken = createIdentifierToken(pathNodes[1].trim());
+            functionRelativeResourcePath.add(idToken);
+        }
+        return functionRelativeResourcePath;
+    }
+
+    private static void extractPathParameterDetails(Operation operation, List functionRelativeResourcePath,
+                                                    String pathNode, String pathParam, List resourceFunctionDocs)
+            throws BallerinaOpenApiException {
+        // check whether path parameter segment has special character
+        String[] split = pathNode.split(CLOSE_CURLY_BRACE, 2);
+        Pattern pattern = Pattern.compile(SPECIAL_CHARACTERS_REGEX);
+        Matcher matcher = pattern.matcher(split[1]);
+        boolean hasSpecialCharacter = matcher.find();
+
+        for (Parameter parameter : operation.getParameters()) {
+            if (parameter.get$ref() != null) {
+                parameter = GeneratorMetaData.getInstance().getOpenAPI().getComponents()
+                        .getParameters().get(extractReferenceType(parameter.get$ref()));
+            }
+            if (parameter.getIn() == null) {
+                continue;
+            }
+            if (pathParam.trim().equals(getValidName(parameter.getName().trim(), false))
+                    && parameter.getIn().equals("path")) {
+                String paramType;
+                if (parameter.getSchema().get$ref() != null) {
+                    paramType = getValidName(extractReferenceType(parameter.getSchema().get$ref()), true);
+                } else {
+                    paramType = convertOpenAPITypeToBallerina(parameter.getSchema());
+                    if (paramType.endsWith(NILLABLE)) {
+                        throw new BallerinaOpenApiException("Path parameter value cannot be null.");
+                    }
+                }
+
+                // TypeDescriptor
+                BuiltinSimpleNameReferenceNode builtSNRNode = createBuiltinSimpleNameReferenceNode(
+                        null,
+                        parameter.getSchema() == null ?
+                                createIdentifierToken(STRING) :
+                                createIdentifierToken(paramType));
+                IdentifierToken paramName = createIdentifierToken(
+                        hasSpecialCharacter ?
+                                getValidName(pathNode, false) :
+                                pathParam);
+                ResourcePathParameterNode resourcePathParameterNode =
+                        createResourcePathParameterNode(
+                                SyntaxKind.RESOURCE_PATH_SEGMENT_PARAM,
+                                createToken(OPEN_BRACKET_TOKEN),
+                                NodeFactory.createEmptyNodeList(),
+                                builtSNRNode,
+                                null,
+                                paramName,
+                                createToken(CLOSE_BRACKET_TOKEN));
+                functionRelativeResourcePath.add(resourcePathParameterNode);
+                functionRelativeResourcePath.add(createToken(SLASH_TOKEN));
+
+                // Add documentation
+                if (resourceFunctionDocs != null) {
+                    String parameterName = paramName.text();
+                    String paramComment = parameter.getDescription() != null && !parameter.getDescription().isBlank() ?
+                            parameter.getDescription() : DEFAULT_PARAM_COMMENT;
+                    MarkdownParameterDocumentationLineNode paramAPIDoc =
+                            DocCommentsGenerator.createAPIParamDoc(parameterName, paramComment);
+                    resourceFunctionDocs.add(paramAPIDoc);
+                }
+                break;
+            }
+        }
+    }
+
+    /**
+     * Method for convert openApi type of format to ballerina type.
+     *
+     * @param schema OpenApi schema
+     * @return ballerina type
+     */
+    public static String convertOpenAPITypeToBallerina(Schema schema) throws BallerinaOpenApiException {
+        String type = getOpenAPIType(schema);
+        if (schema.getEnum() != null && !schema.getEnum().isEmpty() && primitiveTypeList.contains(type)) {
+            EnumGenerator enumGenerator = new EnumGenerator(schema, null);
+            return enumGenerator.generateTypeDescriptorNode().toString();
+        } else if ((INTEGER.equals(type) || NUMBER.equals(type) || STRING.equals(type)) && schema.getFormat() != null) {
+            return convertOpenAPITypeFormatToBallerina(type, schema);
+        } else {
+            if (GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.containsKey(type)) {
+                return GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.get(type);
+            } else {
+                throw new BallerinaOpenApiException("Unsupported OAS data type `" + type + "`");
+            }
+        }
+    }
+
+    /**
+     * This utility is used to select the Ballerina data type for a given OpenAPI type format.
+     *
+     * @param dataType name of the data type. ex: number, integer, string
+     * @param schema uses to generate the type descriptor name ex: int32, int64
+     * @return data type for invalid numeric data formats
+     */
+    private static String convertOpenAPITypeFormatToBallerina(final String dataType, final Schema schema)
+            throws BallerinaOpenApiException {
+        if (OPENAPI_TYPE_TO_FORMAT_MAP.containsKey(dataType) &&
+                OPENAPI_TYPE_TO_FORMAT_MAP.get(dataType).contains(schema.getFormat())) {
+            if (GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.containsKey(schema.getFormat())) {
+                return GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.get(schema.getFormat());
+            } else {
+                OUT_STREAM.printf("WARNING: unsupported format `%s` will be skipped when generating the counterpart " +
+                        "Ballerina type for openAPI schema type: `%s`%n", schema.getFormat(), schema.getType());
+                if (GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.containsKey(dataType)) {
+                    return GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.get(dataType);
+                } else {
+                    throw new BallerinaOpenApiException("Unsupported OAS data type `" + dataType + "`");
+                }
+            }
+        } else {
+            if (GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.containsKey(dataType)) {
+                return GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.get(dataType);
+            } else {
+                throw new BallerinaOpenApiException("Unsupported OAS data type `" + dataType + "`");
+            }
+        }
+    }
+
+    /**
+     * 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(REGEX_ONLY_NUMBERS_OR_NUMBERS_WITH_SPECIAL_CHARACTERS)
+                || identifier.matches(REGEX_WORDS_STARTING_WITH_NUMBERS)) {
+            // this is to handle scenarios 220 => '220, 2023-06-28 => '2023\-06\-28, 3h => '3h
+            return "'" + identifier.replaceAll(GeneratorConstants.ESCAPE_PATTERN, "\\\\$1");
+        } else if (!identifier.matches(REGEX_WITHOUT_SPECIAL_CHARACTERS)) {
+            return identifier.replaceAll(GeneratorConstants.ESCAPE_PATTERN, "\\\\$1");
+        } else if (BAL_KEYWORDS.contains(identifier)) {
+            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 BallerinaOpenApiException - 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 BallerinaOpenApiException {
+
+        if (referenceVariable.startsWith("#") && referenceVariable.contains("/")) {
+            String[] refArray = referenceVariable.split("/");
+            return refArray[refArray.length - 1];
+        } else {
+            throw new BallerinaOpenApiException("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 OpenApi spec from given yaml file.
+     */
+    public static OpenAPI getOpenAPIFromOpenAPIV3Parser(Path definitionPath) throws
+            IOException, BallerinaOpenApiException {
+
+        Path contractPath = java.nio.file.Paths.get(definitionPath.toString());
+        if (!Files.exists(contractPath)) {
+            throw new BallerinaOpenApiException(ErrorMessages.invalidFilePath(definitionPath.toString()));
+        }
+        if (!(definitionPath.toString().endsWith(YAML_EXTENSION) ||
+                definitionPath.toString().endsWith(JSON_EXTENSION) ||
+                definitionPath.toString().endsWith(YML_EXTENSION))) {
+            throw new BallerinaOpenApiException(ErrorMessages.invalidFileType());
+        }
+        String openAPIFileContent = Files.readString(definitionPath);
+        ParseOptions parseOptions = new ParseOptions();
+        parseOptions.setResolve(true);
+        parseOptions.setFlatten(true);
+        SwaggerParseResult parseResult = new OpenAPIParser().readContents(openAPIFileContent, null, parseOptions);
+        if (!parseResult.getMessages().isEmpty()) {
+            if (parseResult.getMessages().contains(UNSUPPORTED_OPENAPI_VERSION_PARSER_MESSAGE)) {
+                throw new BallerinaOpenApiException(ErrorMessages.unsupportedOpenAPIVersion());
+            }
+
+            StringBuilder errorMessage = new StringBuilder("OpenAPI definition has errors: \n");
+            for (String message : parseResult.getMessages()) {
+                errorMessage.append(message).append(LINE_SEPARATOR);
+            }
+
+            throw new BallerinaOpenApiException(errorMessage.toString());
+        }
+        return parseResult.getOpenAPI();
+    }
+
+    /**
+     * Check whether the given media type is currently supported in the tool.
+     *
+     * @param mediaTypeEntry
+     * @return
+     */
+    public static boolean isSupportedMediaType(Map.Entry mediaTypeEntry) {
+        String mediaType = mediaTypeEntry.getKey();
+        String defaultBallerinaType = getBallerinaMediaType(mediaType, true);
+        Schema schema = mediaTypeEntry.getValue().getSchema();
+
+        boolean isValidMultipartFormData = mediaType.equals(MediaType.MULTIPART_FORM_DATA) && schema != null &&
+                (schema.get$ref() != null || schema.getProperties() != null || getOpenAPIType(schema).equals(OBJECT));
+
+        if (defaultBallerinaType.equals(HTTP_REQUEST) && !isValidMultipartFormData) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    /**
+     * Generate BallerinaMediaType for all the return mediaTypes.
+     */
+    public static String getBallerinaMediaType(String mediaType, boolean isRequest) {
+        if (mediaType.matches(".*/json") || mediaType.matches("application/.*\\+json")) {
+            return SyntaxKind.JSON_KEYWORD.stringValue();
+        } else if (mediaType.matches(".*/xml") || mediaType.matches("application/.*\\+xml")) {
+            return SyntaxKind.XML_KEYWORD.stringValue();
+        } else if (mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED) || mediaType.matches("text/.*")) {
+            return STRING_KEYWORD.stringValue();
+        } else if (mediaType.equals(MediaType.APPLICATION_OCTET_STREAM) ||
+                mediaType.equals(IMAGE_PNG) || mediaType.matches("application/.*\\+octet-stream")) {
+            return SyntaxKind.BYTE_KEYWORD.stringValue() + SQUARE_BRACKETS;
+        } else {
+            return isRequest ? HTTP_REQUEST : HTTP_RESPONSE;
+        }
+    }
+
+    /*
+     * Generate variableDeclarationNode.
+     */
+    public static VariableDeclarationNode getSimpleStatement(String responseType, String variable,
+                                                             String initializer) {
+
+        SimpleNameReferenceNode resTypeBind = createSimpleNameReferenceNode(createIdentifierToken(responseType));
+        CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode(createIdentifierToken(variable));
+        TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(resTypeBind, bindingPattern);
+        SimpleNameReferenceNode init = createSimpleNameReferenceNode(createIdentifierToken(initializer));
+
+        return createVariableDeclarationNode(createEmptyNodeList(), null, typedBindingPatternNode,
+                createToken(EQUAL_TOKEN), init, createToken(SEMICOLON_TOKEN));
+    }
+
+    /*
+     * 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, ServerVariables 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]);
+    }
+
+    /**
+     * Create each item of the encoding map.
+     *
+     * @param filedOfMap Includes all the items in the encoding map
+     * @param style      Defines how multiple values are delimited and explode
+     * @param explode    Specifies whether arrays and objects should generate separate parameters
+     * @param key        Key of the item in the map
+     */
+    public static void createEncodingMap(List filedOfMap, String style, Boolean explode, String key) {
+
+        IdentifierToken fieldName = createIdentifierToken('"' + key + '"');
+        Token colon = createToken(COLON_TOKEN);
+        SpecificFieldNode styleField = createSpecificFieldNode(null,
+                createIdentifierToken(STYLE), createToken(COLON_TOKEN),
+                createRequiredExpressionNode(createIdentifierToken(style.toUpperCase(Locale.ROOT))));
+        SpecificFieldNode explodeField = createSpecificFieldNode(null,
+                createIdentifierToken(EXPLODE), createToken(COLON_TOKEN),
+                createRequiredExpressionNode(createIdentifierToken(explode.toString())));
+        ExpressionNode expressionNode = createMappingConstructorExpressionNode(
+                createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(styleField, createToken(COMMA_TOKEN),
+                        explodeField),
+                createToken(CLOSE_BRACE_TOKEN));
+        SpecificFieldNode specificFieldNode = createSpecificFieldNode(null,
+                fieldName, colon, expressionNode);
+        filedOfMap.add(specificFieldNode);
+        filedOfMap.add(createToken(COMMA_TOKEN));
+    }
+
+    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_CURLY_BRACE) &&
+                    pattern.matcher(subPath.split(CLOSE_CURLY_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_CURLY_BRACE) && + pattern.matcher(subPath.split(CLOSE_CURLY_BRACE, 2)[1]).find()) { + String pathParam = subPath; + pathParam = pathParam.substring(pathParam.indexOf(OPEN_CURLY_BRACE) + 1); + pathParam = pathParam.substring(0, pathParam.indexOf(CLOSE_CURLY_BRACE)); + pathParam = getValidName(pathParam, false); + + String[] subPathSplit = subPath.split(CLOSE_CURLY_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 value) { + + if (value.getProperties() != null) { + boolean constraintExists = value.getProperties().values().stream() + .anyMatch(GeneratorUtils::hasConstraints); + if (constraintExists) { + return true; + } + } else if (isComposedSchema(value)) { + 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 (isArraySchema(value)) { + if (!isConstraintExists(value)) { + return isConstraintExists(value.getItems()); + } + } + return isConstraintExists(value); + } + + private static boolean isConstraintExists(Schema 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 || + propertyValue.getPattern() != null; + } + + /** + * Normalized OpenAPI specification with adding proper naming to schema. + * + * @param openAPIPath - openAPI file path + * @return - openAPI specification + * @throws IOException + * @throws BallerinaOpenApiException + */ + public static OpenAPI normalizeOpenAPI(Path openAPIPath, boolean isClient) throws IOException, + BallerinaOpenApiException { + OpenAPI openAPI = getOpenAPIFromOpenAPIV3Parser(openAPIPath); + io.swagger.v3.oas.models.Paths openAPIPaths = openAPI.getPaths(); + if (isClient) { + validateOperationIds(openAPIPaths.entrySet()); + } + validateRequestBody(openAPIPaths.entrySet()); + + if (openAPI.getComponents() != null) { + // Refactor schema name with valid name + Components components = openAPI.getComponents(); + Map componentsSchemas = components.getSchemas(); + if (componentsSchemas != null) { + Map refacSchema = new HashMap<>(); + for (Map.Entry schemaEntry : componentsSchemas.entrySet()) { + String name = getValidName(schemaEntry.getKey(), true); + refacSchema.put(name, schemaEntry.getValue()); + } + openAPI.getComponents().setSchemas(refacSchema); + } + } + return openAPI; + } + + /** + * Check whether an operationId has been defined in each path. If given rename the operationId to accepted format. + * -- ex: GetPetName -> getPetName + * + * @param paths List of paths given in the OpenAPI definition + * @throws BallerinaOpenApiException When operationId is missing in any path + */ + public static void validateOperationIds(Set> paths) throws BallerinaOpenApiException { + List errorList = new ArrayList<>(); + for (Map.Entry entry : paths) { + for (Map.Entry operation : + entry.getValue().readOperationsMap().entrySet()) { + if (operation.getValue().getOperationId() != null) { + String operationId = getValidName(operation.getValue().getOperationId(), false); + operation.getValue().setOperationId(operationId); + } else { + errorList.add(String.format("OperationId is missing in the resource path: %s(%s)", entry.getKey(), + operation.getKey())); + } + } + } + if (!errorList.isEmpty()) { + throw new BallerinaOpenApiException( + "OpenAPI definition has errors: " + LINE_SEPARATOR + String.join(LINE_SEPARATOR, errorList)); + } + } + + /** + * Validate if requestBody found in GET/DELETE/HEAD operation. + * + * @param paths - List of paths given in the OpenAPI definition + * @throws BallerinaOpenApiException - If requestBody found in GET/DELETE/HEAD operation + */ + public static void validateRequestBody(Set> paths) throws BallerinaOpenApiException { + List errorList = new ArrayList<>(); + for (Map.Entry entry : paths) { + if (!entry.getValue().readOperationsMap().isEmpty()) { + for (Map.Entry operation : entry.getValue().readOperationsMap() + .entrySet()) { + String method = operation.getKey().name().trim().toLowerCase(Locale.ENGLISH); + boolean isRequestBodyInvalid = method.equals(GET) || method.equals(HEAD); + if (isRequestBodyInvalid && operation.getValue().getRequestBody() != null) { + errorList.add(method.toUpperCase(Locale.ENGLISH) + " operation cannot have a requestBody. " + + "Error at operationId: " + operation.getValue().getOperationId()); + } + } + } + } + + if (!errorList.isEmpty()) { + StringBuilder errorMessage = new StringBuilder("OpenAPI definition has errors: " + LINE_SEPARATOR); + for (String message : errorList) { + errorMessage.append(message).append(LINE_SEPARATOR); + } + throw new BallerinaOpenApiException(errorMessage.toString()); + } + } + + public static String removeUnusedEntities(SyntaxTree schemaSyntaxTree, String clientContent, String schemaContent, + String serviceContent) throws IOException, FormatterException { + Map tempSourceFiles = new HashMap<>(); + tempSourceFiles.put(CLIENT_FILE_NAME, clientContent); + tempSourceFiles.put(TYPE_FILE_NAME, schemaContent); + if (serviceContent != null) { + tempSourceFiles.put(SERVICE_FILE_NAME, schemaContent); + } + List unusedTypeDefinitionNameList = getUnusedTypeDefinitionNameList(tempSourceFiles); + while (unusedTypeDefinitionNameList.size() > 0) { + ModulePartNode modulePartNode = schemaSyntaxTree.rootNode(); + NodeList members = modulePartNode.members(); + List unusedTypeDefinitionNodeList = new ArrayList<>(); + for (ModuleMemberDeclarationNode node : members) { + if (node.kind().equals(SyntaxKind.TYPE_DEFINITION)) { + for (ChildNodeEntry childNodeEntry : node.childEntries()) { + if (childNodeEntry.name().equals(TYPE_NAME)) { + if (unusedTypeDefinitionNameList.contains(childNodeEntry.node().get().toString())) { + unusedTypeDefinitionNodeList.add(node); + } + } + } + } else if (node.kind().equals(SyntaxKind.ENUM_DECLARATION)) { + for (ChildNodeEntry childNodeEntry : node.childEntries()) { + if (childNodeEntry.name().equals(IDENTIFIER)) { + if (unusedTypeDefinitionNameList.contains(childNodeEntry.node().get().toString())) { + unusedTypeDefinitionNodeList.add(node); + } + } + } + } + } + NodeList modifiedMembers = members.removeAll + (unusedTypeDefinitionNodeList); + ModulePartNode modiedModulePartNode = modulePartNode.modify(modulePartNode.imports(), + modifiedMembers, modulePartNode.eofToken()); + schemaSyntaxTree = schemaSyntaxTree.modifyWith(modiedModulePartNode); + schemaContent = Formatter.format(schemaSyntaxTree).toSourceCode(); + tempSourceFiles.put(TYPE_FILE_NAME, schemaContent); + unusedTypeDefinitionNameList = getUnusedTypeDefinitionNameList(tempSourceFiles); + } + ModulePartNode rootNode = schemaSyntaxTree.rootNode(); + NodeList imports = rootNode.imports(); + imports = removeUnusedImports(rootNode, imports); + + ModulePartNode modiedModulePartNode = rootNode.modify(imports, rootNode.members(), rootNode.eofToken()); + schemaSyntaxTree = schemaSyntaxTree.modifyWith(modiedModulePartNode); + schemaContent = Formatter.format(schemaSyntaxTree).toSourceCode(); + return schemaContent; + } + + private static NodeList removeUnusedImports(ModulePartNode rootNode, + NodeList imports) { + //TODO: This function can be extended to check all the unused imports, for this time only handle constraint + // imports + boolean hasConstraint = false; + NodeList members = rootNode.members(); + for (ModuleMemberDeclarationNode member:members) { + if (member.kind().equals(SyntaxKind.TYPE_DEFINITION)) { + TypeDefinitionNode typeDefNode = (TypeDefinitionNode) member; + if (typeDefNode.typeDescriptor().kind().equals(SyntaxKind.RECORD_TYPE_DESC)) { + RecordTypeDescriptorNode record = (RecordTypeDescriptorNode) typeDefNode.typeDescriptor(); + NodeList fields = record.fields(); + //Traverse record fields to check for constraints + for (Node node: fields) { + if (node instanceof RecordFieldNode) { + RecordFieldNode recField = (RecordFieldNode) node; + if (recField.metadata().isPresent()) { + hasConstraint = traverseAnnotationNode(recField.metadata(), hasConstraint); + } + } + if (hasConstraint) { + break; + } + } + } + + if (typeDefNode.metadata().isPresent()) { + hasConstraint = traverseAnnotationNode(typeDefNode.metadata(), hasConstraint); + } + } + if (hasConstraint) { + break; + } + } + if (!hasConstraint) { + for (ImportDeclarationNode importNode: imports) { + if (importNode.orgName().isPresent()) { + if (importNode.orgName().get().toString().equals("ballerina/") && + importNode.moduleName().get(0).text().equals(CONSTRAINT)) { + imports = imports.remove(importNode); + } + } + } + } + return imports; + } + + private static boolean traverseAnnotationNode(Optional recField, boolean hasConstraint) { + MetadataNode metadata = recField.get(); + for (AnnotationNode annotation : metadata.annotations()) { + String annotationRef = annotation.annotReference().toString(); + if (annotationRef.startsWith(CONSTRAINT)) { + hasConstraint = true; + break; + } + } + return hasConstraint; + } + + private static List getUnusedTypeDefinitionNameList(Map srcFiles) throws IOException { + List unusedTypeDefinitionNameList = new ArrayList<>(); + Path tmpDir = Files.createTempDirectory(".openapi-tmp" + System.nanoTime()); + writeFilesTemp(srcFiles, tmpDir); + if (Files.exists(tmpDir.resolve(CLIENT_FILE_NAME)) && Files.exists(tmpDir.resolve(TYPE_FILE_NAME)) && + Files.exists(tmpDir.resolve(BALLERINA_TOML))) { + SemanticModel semanticModel = getSemanticModel(tmpDir.resolve(CLIENT_FILE_NAME)); + List symbols = semanticModel.moduleSymbols(); + for (Symbol symbol : symbols) { + if (symbol.kind().equals(SymbolKind.TYPE_DEFINITION) || symbol.kind().equals(SymbolKind.ENUM)) { + List references = semanticModel.references(symbol); + if (references.size() == 1) { + unusedTypeDefinitionNameList.add(symbol.getName().get()); + } + } + } + } + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + FileUtils.deleteDirectory(tmpDir.toFile()); + } catch (IOException ex) { + LOGGER.error("Unable to delete the temporary directory : " + tmpDir, ex); + } + })); + return unusedTypeDefinitionNameList; + } + + private static void writeFilesTemp(Map srcFiles, Path tmpDir) throws IOException { + srcFiles.put(BALLERINA_TOML, BALLERINA_TOML_CONTENT); + PrintWriter writer = null; + for (Map.Entry entry : srcFiles.entrySet()) { + String key = entry.getKey(); + Path filePath = tmpDir.resolve(key); + try { + writer = new PrintWriter(filePath.toString(), "UTF-8"); + writer.print(entry.getValue()); + } finally { + if (writer != null) { + writer.close(); + } + } + } + } + + private static SemanticModel getSemanticModel(Path clientPath) throws ProjectException { + // Load project instance for single ballerina file + try { + Project project = ProjectLoader.loadProject(clientPath); + Package packageName = project.currentPackage(); + DocumentId docId; + + if (project.kind().equals(ProjectKind.BUILD_PROJECT)) { + docId = project.documentId(clientPath); + } 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()); + } catch (ProjectException e) { + throw new ProjectException(e.getMessage()); + } + } + + public static String getOpenAPIType(Schema schema) { + if (schema.getTypes() != null && !schema.getTypes().isEmpty()) { + for (String type : schema.getTypes()) { + // TODO: https://github.com/ballerina-platform/openapi-tools/issues/1497 + // this returns the first non-null type in the list + if (!type.equals(NULL)) { + return type; + } + } + } else if (schema.getType() != null) { + return schema.getType(); + } + return null; + } + + public static boolean isArraySchema(Schema schema) { + return getOpenAPIType(schema) != null && Objects.equals(getOpenAPIType(schema), ARRAY); + } + + public static boolean isMapSchema(Schema schema) { + return schema.getAdditionalProperties() != null; + } + + public static boolean isObjectSchema(Schema schema) { + return getOpenAPIType(schema) != null && Objects.equals(getOpenAPIType(schema), OBJECT); + } + + public static boolean isComposedSchema(Schema schema) { + return schema.getAnyOf() != null || schema.getOneOf() != null || + schema.getAllOf() != null; + } + + public static boolean isStringSchema(Schema schema) { + return getOpenAPIType(schema) != null && Objects.equals(getOpenAPIType(schema), STRING); + } + + public static boolean isBooleanSchema(Schema schema) { + return getOpenAPIType(schema) != null && Objects.equals(getOpenAPIType(schema), BOOLEAN); + } + + public static boolean isIntegerSchema(Schema fieldSchema) { + return Objects.equals(GeneratorUtils.getOpenAPIType(fieldSchema), INTEGER); + } + + public static boolean isNumberSchema(Schema fieldSchema) { + return Objects.equals(GeneratorUtils.getOpenAPIType(fieldSchema), NUMBER); + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/exception/BallerinaOpenApiException.java b/openapi-core/src/main/java/io/ballerina/openapi/core/exception/BallerinaOpenApiException.java new file mode 100644 index 000000000..b226c481d --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/exception/BallerinaOpenApiException.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.exception; + +/** + * Exception type definition for OpenAPI to Ballerina parsing related errors. + * + * @since 1.3.0 + */ +public class BallerinaOpenApiException extends Exception { + public BallerinaOpenApiException(String message, Throwable e) { + super(message, e); + } + + public BallerinaOpenApiException(String message) { + super(message); + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaAuthConfigGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaAuthConfigGenerator.java similarity index 53% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaAuthConfigGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaAuthConfigGenerator.java index 6059218ed..40120573c 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaAuthConfigGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaAuthConfigGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client; +package io.ballerina.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.AnnotationNode; @@ -27,6 +27,7 @@ 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.DoStatementNode; import io.ballerina.compiler.syntax.tree.ElseBlockNode; import io.ballerina.compiler.syntax.tree.ExpressionNode; import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; @@ -34,10 +35,11 @@ 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.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; import io.ballerina.compiler.syntax.tree.MetadataNode; -import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; -import io.ballerina.compiler.syntax.tree.NilLiteralNode; +import io.ballerina.compiler.syntax.tree.MethodCallExpressionNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.NodeList; @@ -51,30 +53,37 @@ 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.TypedBindingPatternNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.DocCommentsGenerator; -import io.ballerina.openapi.generators.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.security.SecurityScheme; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +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.NodeFactory.createAnnotationNode; 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; @@ -83,6 +92,7 @@ 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.createDoStatementNode; 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; @@ -93,20 +103,25 @@ 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.createNilLiteralNode; 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.createRecordTypeDescriptorNode; 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.createRestArgumentNode; 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.createTypeDefinitionNode; 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; @@ -114,9 +129,12 @@ 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.DO_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ELLIPSIS_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; @@ -126,6 +144,7 @@ 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; @@ -133,33 +152,59 @@ 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; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEYS_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG_PARAM; -import static io.ballerina.openapi.generators.GeneratorConstants.AUTH; -import static io.ballerina.openapi.generators.GeneratorConstants.AUTH_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.AUTH_CONFIG_RECORD; -import static io.ballerina.openapi.generators.GeneratorConstants.AuthConfigTypes; -import static io.ballerina.openapi.generators.GeneratorConstants.BASIC; -import static io.ballerina.openapi.generators.GeneratorConstants.BEARER; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_CRED; -import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG_RECORD_ARG; -import static io.ballerina.openapi.generators.GeneratorConstants.HTTP; -import static io.ballerina.openapi.generators.GeneratorConstants.OAUTH2; -import static io.ballerina.openapi.generators.GeneratorConstants.PASSWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.PROXY_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.REFRESH_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.SELF; -import static io.ballerina.openapi.generators.GeneratorConstants.SSL_FIELD_NAME; -import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEY; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEYS_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEY_CONFIG_PARAM; +import static io.ballerina.openapi.core.GeneratorConstants.AUTH; +import static io.ballerina.openapi.core.GeneratorConstants.AuthConfigTypes; +import static io.ballerina.openapi.core.GeneratorConstants.BASIC; +import static io.ballerina.openapi.core.GeneratorConstants.BEARER; +import static io.ballerina.openapi.core.GeneratorConstants.BOOLEAN; +import static io.ballerina.openapi.core.GeneratorConstants.CACHE_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.CACHE_CONFIG_FIELD; +import static io.ballerina.openapi.core.GeneratorConstants.CHUNKING; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_CRED; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_HTTP1_SETTINGS; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_HTTP1_SETTINGS_FIELD; +import static io.ballerina.openapi.core.GeneratorConstants.CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.CONNECTION_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_HTTP_VERSION; +import static io.ballerina.openapi.core.GeneratorConstants.ENSURE_TYPE; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP2_SETTINGS; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP2_SETTINGS_FIELD; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_CLIENT_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_VERIONS_EXT; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_VERSION; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_VERSION_MAP; +import static io.ballerina.openapi.core.GeneratorConstants.KEEP_ALIVE; +import static io.ballerina.openapi.core.GeneratorConstants.OAUTH2; +import static io.ballerina.openapi.core.GeneratorConstants.PASSWORD; +import static io.ballerina.openapi.core.GeneratorConstants.PROXY; +import static io.ballerina.openapi.core.GeneratorConstants.PROXY_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.REFRESH_TOKEN; +import static io.ballerina.openapi.core.GeneratorConstants.RESPONSE_LIMIT; +import static io.ballerina.openapi.core.GeneratorConstants.RESPONSE_LIMIT_FIELD; +import static io.ballerina.openapi.core.GeneratorConstants.SECURE_SOCKET; +import static io.ballerina.openapi.core.GeneratorConstants.SECURE_SOCKET_FIELD; +import static io.ballerina.openapi.core.GeneratorConstants.SELF; +import static io.ballerina.openapi.core.GeneratorConstants.SETTINGS; +import static io.ballerina.openapi.core.GeneratorConstants.SSL_FIELD_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.STRING; +import static io.ballerina.openapi.core.GeneratorConstants.VALIDATION; +import static io.ballerina.openapi.core.GeneratorConstants.X_BALLERINA_HTTP_CONFIGURATIONS; +import static io.ballerina.openapi.core.GeneratorUtils.escapeIdentifier; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; /** * This class is used to generate authentication related nodes of the ballerina connector client syntax tree. + * + * @since 1.3.0 */ public class BallerinaAuthConfigGenerator { + private final Map headerApiKeyNameList = new HashMap<>(); private final Map queryApiKeyNameList = new HashMap<>(); private final List apiKeysConfigRecordFields = new ArrayList<>(); @@ -168,8 +213,11 @@ public class BallerinaAuthConfigGenerator { private String clientCredGrantTokenUrl; private String passwordGrantTokenUrl; private String refreshTokenUrl; + private String httpVersion = HTTP_VERSION_MAP.get(DEFAULT_HTTP_VERSION); private final Set authTypes = new LinkedHashSet<>(); + private List authRelatedTypeDefinitionNodes = new ArrayList<>(); + public BallerinaAuthConfigGenerator(boolean isAPIKey, boolean isHttpOROAuth) { this.apiKey = isAPIKey; this.httpOROAuth = isHttpOROAuth; @@ -190,6 +238,7 @@ public boolean isApiKey() { * @return {@link boolean} */ public boolean isHttpOROAuth() { + return httpOROAuth; } @@ -217,25 +266,53 @@ public Map getHeaderApiKeyNameList() { * @return {@link Set} */ public Set getAuthType() { + return authTypes; } + public List getAuthRelatedTypeDefinitionNodes() { + return authRelatedTypeDefinitionNodes; + } + /** * Add authentication related records. * - * @param openAPI OpenAPI object received from swagger open-api parser - * @param nodes List of ModuleMemberDeclarationNode nodes - * @throws BallerinaOpenApiException When function fails + * @param openAPI OpenAPI object received from swagger open-api parser + * @throws BallerinaOpenApiException When function fails */ - public void addAuthRelatedRecords (OpenAPI openAPI, List nodes) throws + public void addAuthRelatedRecords(OpenAPI openAPI) throws BallerinaOpenApiException { - if (openAPI.getComponents() != null && openAPI.getComponents().getSecuritySchemes() != null) { - // Add ApiKeysConfig or ClientConfig record - nodes.add(getConfigRecord(openAPI)); + List nodes = new ArrayList<>(); + if (openAPI.getComponents() != null) { + // set auth types + if (openAPI.getComponents().getSecuritySchemes() != null) { + Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); + setAuthTypes(securitySchemeMap); + } - // Add `AuthConfig` record if combination of ApiKey and HTTP/OAuth authentication is supported - if (isApiKey() && isHttpOROAuth()) { - nodes.add(getAuthConfigRecord()); + // TODO: Handle the scenarion when invalid http version is given. + // No diagnosics available at this level to send a warning. + // Currently ignore the values and gen with default. + if (openAPI.getExtensions() != null && + openAPI.getExtensions().containsKey(X_BALLERINA_HTTP_CONFIGURATIONS)) { + LinkedHashMap extFields = + (LinkedHashMap) openAPI.getExtensions().get(X_BALLERINA_HTTP_CONFIGURATIONS); + if (extFields.containsKey(HTTP_VERIONS_EXT)) { + String httpVersion = extFields.get(HTTP_VERIONS_EXT); + if (httpVersion != null && HTTP_VERSION_MAP.containsKey(httpVersion)) { + this.httpVersion = HTTP_VERSION_MAP.get(httpVersion); + } + } + } + + // generate related records + TypeDefinitionNode connectionConfigRecord = generateConnectionConfigRecord(); + TypeDefinitionNode clientHttp1SettingsRecord = getClientHttp1SettingsRecord(); + TypeDefinitionNode customProxyConfigRecord = getCustomProxyRecord(); + nodes.addAll(Arrays.asList(connectionConfigRecord, clientHttp1SettingsRecord, customProxyConfigRecord)); + + if (isApiKey()) { + nodes.add(generateApiKeysConfig()); } // Add custom `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl if `tokenUrl` is available @@ -253,6 +330,7 @@ public void addAuthRelatedRecords (OpenAPI openAPI, List * # Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. - * public type ClientConfig record {| + * @display {label: "Connection Config"} + * public type ConnectionConfig record {| * # Configurations related to client authentication * http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig auth; * # The HTTP version understood by the client @@ -293,39 +372,60 @@ public void addAuthRelatedRecords (OpenAPI openAPI, List - * -- ex: Config record for API Key Authentication mechanism. + * Scenario 1 : For openapi contracts with no authentication mechanism given, auth field will not be generated + * Scenario 2 : For openapi contracts with authentication mechanism, auth field in relevant types will be generated + * Scenario 3 : For openapi contracts with only apikey authentication mechanism, auth field will not be generated + * Scenario 4 : For openapi 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)); + return node; + + } + + /** + * Generate the ApiKeysConfig record when the api-key auth type is given. *
-     *     # Provides API key configurations needed when communicating with a remote HTTP endpoint.
-     *     public type ApiKeysConfig record {
-     *          # API keys related to connector authentication
-     *          map apiKeys;
-     *     };
+     *  # Provides API key configurations needed when communicating with a remote HTTP endpoint.
+     *  public type ApiKeysConfig record {|
+     *     # Represents API Key `Authorization`
+     *     @display {label: "", kind: "password"}
+     *     string authorization;
+     *     # Represents API Key `apikey`
+     *     @display {label: "", kind: "password"}
+     *     string apikey;
+     *  |};
      * 
* - * @param openAPI OpenApi object received from swagger open-api parser * @return {@link TypeDefinitionNode} Syntax tree node of config record */ - public TypeDefinitionNode getConfigRecord(OpenAPI openAPI) throws BallerinaOpenApiException { - Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); - setAuthTypes(securitySchemeMap); - Token typeName; - NodeList recordFieldList; - MetadataNode configRecordMetadataNode; - if (apiKey) { - configRecordMetadataNode = getMetadataNode( - "Provides API key configurations needed when communicating " + - "with a remote HTTP endpoint."); - typeName = AbstractNodeFactory.createIdentifierToken(API_KEYS_CONFIG); - recordFieldList = createNodeList(apiKeysConfigRecordFields); - } else { - configRecordMetadataNode = getMetadataNode( - "Provides a set of configurations for controlling the behaviours when communicating " + - "with a remote HTTP endpoint."); - typeName = AbstractNodeFactory.createIdentifierToken(CLIENT_CONFIG); - recordFieldList = createNodeList(getClientConfigRecordFields()); - } + public TypeDefinitionNode generateApiKeysConfig() { + MetadataNode configRecordMetadataNode = getMetadataNode( + "Provides API key configurations needed when communicating " + + "with a remote HTTP 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, @@ -333,7 +433,6 @@ public TypeDefinitionNode getConfigRecord(OpenAPI openAPI) throws BallerinaOpenA return NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); - } /** @@ -350,7 +449,7 @@ public TypeDefinitionNode getConfigRecord(OpenAPI openAPI) throws BallerinaOpenA * * @return {@link TypeDefinitionNode} Custom `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl */ - public TypeDefinitionNode getOAuth2ClientCredsGrantConfigRecord() { + private TypeDefinitionNode getOAuth2ClientCredsGrantConfigRecord() { Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_CLIENT_CREDENTIAL.getValue()); NodeList recordFieldList = createNodeList(getClientCredsGrantConfigFields()); MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Client Credentials Grant Configs"); @@ -409,7 +508,7 @@ private List getClientCredsGrantConfigFields() { * * @return {@link TypeDefinitionNode} Custom `OAuth2PasswordGrantConfig` record with default tokenUrl */ - public TypeDefinitionNode getOAuth2PasswordGrantConfigRecord() { + private TypeDefinitionNode getOAuth2PasswordGrantConfigRecord() { Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_PASSWORD.getValue()); NodeList recordFieldList = createNodeList(getPasswordGrantConfigFields()); MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Password Grant Configs"); @@ -434,6 +533,7 @@ public TypeDefinitionNode getOAuth2PasswordGrantConfigRecord() { * @return {@link List} */ private List getPasswordGrantConfigFields() { + List recordFieldNodes = new ArrayList<>(); Token semicolonToken = createToken(SEMICOLON_TOKEN); Token equalToken = createToken(EQUAL_TOKEN); @@ -468,7 +568,7 @@ private List getPasswordGrantConfigFields() { * * @return {@link TypeDefinitionNode} Custom `OAuth2RefreshTokenGrantConfig` record with default refreshUrl */ - public TypeDefinitionNode getOAuth2RefreshTokenGrantConfigRecord() { + private TypeDefinitionNode getOAuth2RefreshTokenGrantConfigRecord() { Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_REFRESH_TOKEN.getValue()); NodeList recordFieldList = createNodeList(getRefreshTokenGrantConfigFields()); MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Refresh Token Grant Configs"); @@ -493,6 +593,7 @@ public TypeDefinitionNode getOAuth2RefreshTokenGrantConfigRecord() { * @return {@link List} */ private List getRefreshTokenGrantConfigFields() { + List recordFieldNodes = new ArrayList<>(); Token semicolonToken = createToken(SEMICOLON_TOKEN); Token equalToken = createToken(EQUAL_TOKEN); @@ -514,30 +615,66 @@ private List getRefreshTokenGrantConfigFields() { } /** - * Generate `AuthConfig` record when combination of ApiKey and HTTPOrOAuth authentication is supported. + * Generates`ClientHttp1Settings` record. * *
-     *     # Provides Auth configurations needed when communicating with a remote HTTP endpoint.
-     *     public type AuthConfig record {|
-     *         # Auth Configuration
-     *         http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig|ApiKeysConfig auth;
-     *     |};
+     *  # Provides settings related to HTTP/1.x protocol.
+     *  public type ClientHttp1Settings record {|
+     *     # Specifies whether to reuse a connection for multiple requests
+     *     http:KeepAlive keepAlive = http:KEEPALIVE_AUTO;
+     *     # The chunking behaviour of the request
+     *     http:Chunking chunking = http:CHUNKING_AUTO;
+     *     # Proxy server related options
+     *     ProxyConfig proxy?;
+     *  |};
      * 
* - * @return {@link TypeDefinitionNode} Syntax tree node of config record + * @return {@link TypeDefinitionNode} */ - public TypeDefinitionNode getAuthConfigRecord() { - Token typeName = AbstractNodeFactory.createIdentifierToken(AUTH_CONFIG_RECORD); - NodeList recordFieldList = createNodeList(getAuthConfigRecordFields()); - MetadataNode configRecordMetadataNode = getMetadataNode("Provides Auth configurations needed when " + - "communicating with a remote HTTP endpoint."); - 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)); + private TypeDefinitionNode getClientHttp1SettingsRecord() { + Token recordTypeName = createIdentifierToken(CLIENT_HTTP1_SETTINGS); + NodeList recordFieldList = createNodeList(getClientHttp1SettingsRecordFields()); + MetadataNode recordMetadataNode = getMetadataNode( + "Provides settings related to HTTP/1.x protocol."); + RecordTypeDescriptorNode recordTypeDescriptorNode = createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return createTypeDefinitionNode(recordMetadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), + recordTypeName, recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + + } + + /** + * Generates`ProxyConfig` record. + * + *
+     *  # Proxy server configurations to be used with the HTTP client endpoint.
+     *  public type ProxyConfig record {|
+     *     # Host name of the proxy server
+     *     string host = "";
+     *     # Proxy server port
+     *     int port = 0;
+     *     # Proxy server username
+     *     string userName = "";
+     *     # Proxy server password
+     *     @display {label: "", kind: "password"}
+     *     string password = "";
+     *  |};
+     * 
+ * + * @return {@link TypeDefinitionNode} + */ + private TypeDefinitionNode getCustomProxyRecord() { + Token recordTypeName = createIdentifierToken("ProxyConfig"); + NodeList recordFieldList = createNodeList(getCustomProxyRecordFields()); + MetadataNode recordMetadataNode = getMetadataNode( + "Proxy server configurations to be used with the HTTP client endpoint."); + RecordTypeDescriptorNode recordTypeDescriptorNode = createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return createTypeDefinitionNode(recordMetadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), + recordTypeName, recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } /** @@ -568,46 +705,39 @@ public ObjectFieldNode getApiKeyMapClassVariable() { // return ObjectFieldNode /** * 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://petstore.swagger.io:443/v2" } + * {@code ClientConfig clientConfig, string serviceUrl = "https://petstore.swagger.io:443/v2" } * -- ex: Config param for API Key Authentication mechanism. - * {@code ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, - * string serviceUrl = "https://petstore.swagger.io:443/v2" } - * Config param for API Key Authentication mechanism with no server URL given - * {@code ApiKeysConfig apiKeyConfig, string serviceUrl; http:ClientConfiguration clientConfig = {}} + * {@code ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, + * string serviceUrl = "https://petstore.swagger.io: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://petstore.swagger.io:443/v2" } - * Config param when no authentication mechanism given with no server URL - * {@code string serviceUrl, http:ClientConfiguration clientConfig = {}} + * {@code http:ClientConfiguration clientConfig = {}, + * string serviceUrl = "https://petstore.swagger.io: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, http:ClientConfiguration clientConfig = {}, - * string serviceUrl = "https://petstore.swagger.io:443/v2" } + * {@code AuthConfig authConfig,ConnectionConfig config = {}, + * string serviceUrl = "https://petstore.swagger.io:443/v2" } * * @return {@link List} syntax tree node list of config parameters */ public List getConfigParamForClassInit(String serviceUrl) { + NodeList annotationNodes = createEmptyNodeList(); Node serviceURLNode = getServiceURLNode(serviceUrl); List parameters = new ArrayList<>(); IdentifierToken equalToken = createIdentifierToken(GeneratorConstants.EQUAL); - if (httpOROAuth && !apiKey) { + if (httpOROAuth) { BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(CLIENT_CONFIG)); - IdentifierToken paramName = createIdentifierToken(CONFIG_RECORD_ARG); + createIdentifierToken(CONNECTION_CONFIG)); + IdentifierToken paramName = createIdentifierToken(CONFIG); RequiredParameterNode authConfig = createRequiredParameterNode(annotationNodes, typeName, paramName); parameters.add(authConfig); parameters.add(createToken(COMMA_TOKEN)); parameters.add(serviceURLNode); } else { - if (apiKey && httpOROAuth) { - BuiltinSimpleNameReferenceNode authConfigTypeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(AUTH_CONFIG_RECORD)); - IdentifierToken authConfigParamName = createIdentifierToken(AUTH_CONFIG); - RequiredParameterNode authConfigParamNode = createRequiredParameterNode(annotationNodes, - authConfigTypeName, authConfigParamName); - parameters.add(authConfigParamNode); - parameters.add(createToken(COMMA_TOKEN)); - } else if (apiKey) { + if (apiKey) { BuiltinSimpleNameReferenceNode apiKeyConfigTypeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(API_KEYS_CONFIG)); IdentifierToken apiKeyConfigParamName = createIdentifierToken(API_KEY_CONFIG_PARAM); @@ -616,19 +746,20 @@ public List getConfigParamForClassInit(String serviceUrl) { parameters.add(apiKeyConfigParamNode); parameters.add(createToken(COMMA_TOKEN)); } + BuiltinSimpleNameReferenceNode httpClientConfigTypeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken("http:ClientConfiguration")); - IdentifierToken httpClientConfig = createIdentifierToken(CONFIG_RECORD_ARG); + createIdentifierToken(CONNECTION_CONFIG)); + IdentifierToken httpClientConfig = createIdentifierToken(CONFIG); BasicLiteralNode emptyexpression = createBasicLiteralNode(null, createIdentifierToken(" {}")); - DefaultableParameterNode defaultHTTPConfig = createDefaultableParameterNode(annotationNodes, + DefaultableParameterNode defaultConnectionConfig = createDefaultableParameterNode(annotationNodes, httpClientConfigTypeName, httpClientConfig, equalToken, emptyexpression); if (serviceURLNode instanceof RequiredParameterNode) { parameters.add(serviceURLNode); parameters.add(createToken(COMMA_TOKEN)); - parameters.add(defaultHTTPConfig); + parameters.add(defaultConnectionConfig); } else { - parameters.add(defaultHTTPConfig); + parameters.add(defaultConnectionConfig); parameters.add(createToken(COMMA_TOKEN)); parameters.add(serviceURLNode); } @@ -638,9 +769,10 @@ public List getConfigParamForClassInit(String serviceUrl) { /** * Generate the serviceUrl parameters of the client class init method. - * @param serviceUrl service Url given in the OpenAPI file - * @return {@link DefaultableParameterNode} when server URl is given in the OpenAPI file - * {@link RequiredParameterNode} when server URL is not given in the OpenAPI file + * + * @param serviceUrl service Url given in the OpenAPI file + * @return {@link DefaultableParameterNode} when server URl is given in the OpenAPI file + * {@link RequiredParameterNode} when server URL is not given in the OpenAPI file */ private Node getServiceURLNode(String serviceUrl) { Node serviceURLNode; @@ -660,6 +792,271 @@ private Node getServiceURLNode(String serviceUrl) { return serviceURLNode; } + /** + * Generate if-else statements for the do block in client init function. + *
+     *     if config.http1Settings is ClientHttp1Settings {
+     *         ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings);
+     *         httpClientConfig.http1Settings = {...settings};
+     *     }
+     * 
+ * @param fieldName name of the field + * @param fieldType type of the field + * @return + */ + private IfElseStatementNode getDoBlockIfElseStatementNodes(String fieldName, String fieldType) { + ExpressionNode expressionNode = createFieldAccessExpressionNode( + createRequiredExpressionNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(fieldName))); + + ExpressionNode condition = createBinaryExpressionNode(null, + expressionNode, + createToken(IS_KEYWORD), + createIdentifierToken(fieldType) + ); + + List statementNodes = new ArrayList<>(); + + // httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + FieldAccessExpressionNode fieldAccessExpressionNode = createFieldAccessExpressionNode( + createRequiredExpressionNode(createIdentifierToken(HTTP_CLIENT_CONFIG)), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(fieldName))); + + MethodCallExpressionNode methodCallExpressionNode = createMethodCallExpressionNode( + createFieldAccessExpressionNode(createRequiredExpressionNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(fieldName))), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(ENSURE_TYPE)), + createToken(OPEN_PAREN_TOKEN), + createSeparatedNodeList(createPositionalArgumentNode( + createRequiredExpressionNode(createIdentifierToken(fieldType)))), + createToken(CLOSE_PAREN_TOKEN)); + CheckExpressionNode checkExpressionNode = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), + methodCallExpressionNode); + AssignmentStatementNode varAssignmentNode = createAssignmentStatementNode(fieldAccessExpressionNode, + createToken(EQUAL_TOKEN), checkExpressionNode, createToken(SEMICOLON_TOKEN)); + statementNodes.add(varAssignmentNode); + + NodeList statementList = createNodeList(statementNodes); + BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), statementList, + createToken(CLOSE_BRACE_TOKEN)); + return createIfElseStatementNode(createToken(IF_KEYWORD), condition, + ifBody, null); + } + + /** + * Generate do block in client init function. + * + * @return {@link DoStatementNode} + */ + public DoStatementNode getClientConfigDoStatementNode() { + List doStatementNodeList = new ArrayList<>(); + // ClientHttp1Settings if statement + { + ExpressionNode expressionNode = createFieldAccessExpressionNode( + createRequiredExpressionNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode( + createIdentifierToken(CLIENT_HTTP1_SETTINGS_FIELD))); + + ExpressionNode condition = createBinaryExpressionNode(null, + expressionNode, + createToken(IS_KEYWORD), + createIdentifierToken(CLIENT_HTTP1_SETTINGS) + ); + + List statementNodes = new ArrayList<>(); + + // ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + SimpleNameReferenceNode typeBindingPattern = createSimpleNameReferenceNode( + createIdentifierToken(CLIENT_HTTP1_SETTINGS)); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( + createIdentifierToken(SETTINGS)); + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, + bindingPattern); + MethodCallExpressionNode methodCallExpressionNode = createMethodCallExpressionNode( + createFieldAccessExpressionNode(createRequiredExpressionNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_HTTP1_SETTINGS_FIELD))), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(ENSURE_TYPE)), + createToken(OPEN_PAREN_TOKEN), + createSeparatedNodeList(createPositionalArgumentNode( + createRequiredExpressionNode(createIdentifierToken(CLIENT_HTTP1_SETTINGS)))), + createToken(CLOSE_PAREN_TOKEN)); + CheckExpressionNode checkExpressionNode = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), + methodCallExpressionNode); + AssignmentStatementNode varAssignmentNode = createAssignmentStatementNode(typedBindingPatternNode, + createToken(EQUAL_TOKEN), checkExpressionNode, createToken(SEMICOLON_TOKEN)); + statementNodes.add(varAssignmentNode); + + // httpClientConfig.http1Settings = {...settings}; + FieldAccessExpressionNode fieldAccessExpressionNode = createFieldAccessExpressionNode( + createRequiredExpressionNode(createIdentifierToken(HTTP_CLIENT_CONFIG)), + createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_HTTP1_SETTINGS_FIELD))); + MappingConstructorExpressionNode mappingConstructorExpressionNode = createMappingConstructorExpressionNode( + createToken(OPEN_BRACE_TOKEN), + createSeparatedNodeList( + createRestArgumentNode(createToken(ELLIPSIS_TOKEN), + createRequiredExpressionNode(createIdentifierToken(SETTINGS)))), + createToken(CLOSE_BRACE_TOKEN)); + + AssignmentStatementNode fieldAssignmentNode = createAssignmentStatementNode(fieldAccessExpressionNode, + createToken(EQUAL_TOKEN), mappingConstructorExpressionNode, createToken(SEMICOLON_TOKEN)); + + statementNodes.add(fieldAssignmentNode); + + NodeList statementList = createNodeList(statementNodes); + BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), statementList, + createToken(CLOSE_BRACE_TOKEN)); + + IfElseStatementNode ifElseStatementNode = createIfElseStatementNode(createToken(IF_KEYWORD), condition, + ifBody, null); + doStatementNodeList.add(ifElseStatementNode); + } + // http:ClientHttp2Settings if statement + doStatementNodeList.addAll(Arrays.asList( + getDoBlockIfElseStatementNodes(HTTP2_SETTINGS_FIELD, HTTP2_SETTINGS), + getDoBlockIfElseStatementNodes(CACHE_CONFIG_FIELD, CACHE_CONFIG), + getDoBlockIfElseStatementNodes(RESPONSE_LIMIT_FIELD, RESPONSE_LIMIT), + getDoBlockIfElseStatementNodes(SECURE_SOCKET_FIELD, SECURE_SOCKET), + getDoBlockIfElseStatementNodes(PROXY_CONFIG, PROXY))); + + BlockStatementNode blockStatementNode = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), + createNodeList(doStatementNodeList), createToken(CLOSE_BRACE_TOKEN)); + + return createDoStatementNode(createToken(DO_KEYWORD), + blockStatementNode, null); + } + + /** + * Generate `httpClientConfig` variable. + *
+     *        http:ClientConfiguration httpClientConfig = {
+     *             httpVersion: config.httpVersion,
+     *             timeout: config.timeout,
+     *             forwarded: config.forwarded,
+     *             poolConfig: config.poolConfig,
+     *             compression: config.compression,
+     *             circuitBreaker: config.circuitBreaker,
+     *             retryConfig: config.retryConfig,
+     *             validation: config.validation
+     *         };
+     * 
+ * + * @return + */ + public VariableDeclarationNode getHttpClientConfigVariableNode() { + Token comma = createToken(COMMA_TOKEN); + NodeList annotationNodes = createEmptyNodeList(); + // http:ClientConfiguration variable declaration + SimpleNameReferenceNode typeBindingPattern = createSimpleNameReferenceNode( + createIdentifierToken("http:ClientConfiguration")); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( + createIdentifierToken(HTTP_CLIENT_CONFIG)); + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, + bindingPattern); + + List argumentsList = new ArrayList<>(); + + if (isHttpOROAuth() && !isApiKey()) { + ExpressionNode authValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(AUTH))); + SpecificFieldNode authField = createSpecificFieldNode(null, + createIdentifierToken(AUTH), + createToken(COLON_TOKEN), authValExp); + argumentsList.add(authField); + argumentsList.add(comma); + } + + // create httpVersion field + ExpressionNode httpVersionValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("httpVersion"))); + SpecificFieldNode httpVersionField = createSpecificFieldNode(null, + createIdentifierToken("httpVersion"), + createToken(COLON_TOKEN), httpVersionValExp); + argumentsList.add(httpVersionField); + argumentsList.add(comma); + // create timeout field + ExpressionNode timeoutValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("timeout"))); + SpecificFieldNode timeoutField = createSpecificFieldNode(null, + createIdentifierToken("timeout"), + createToken(COLON_TOKEN), timeoutValExp); + argumentsList.add(timeoutField); + argumentsList.add(comma); + + // create forwarded field + ExpressionNode forwardedValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("forwarded"))); + SpecificFieldNode forwardedField = createSpecificFieldNode(null, + createIdentifierToken("forwarded"), + createToken(COLON_TOKEN), forwardedValExp); + argumentsList.add(forwardedField); + argumentsList.add(comma); + + // create poolConfig field + ExpressionNode poolConfigValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("poolConfig"))); + SpecificFieldNode poolConfigField = createSpecificFieldNode(null, + createIdentifierToken("poolConfig"), + createToken(COLON_TOKEN), poolConfigValExp); + argumentsList.add(poolConfigField); + argumentsList.add(comma); + + // create compression field + ExpressionNode compressionValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("compression"))); + SpecificFieldNode compressionField = createSpecificFieldNode(null, + createIdentifierToken("compression"), + createToken(COLON_TOKEN), compressionValExp); + argumentsList.add(compressionField); + argumentsList.add(comma); + + // create circuitBreaker field + ExpressionNode circuitBreakerValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("circuitBreaker"))); + SpecificFieldNode circuitBreakerField = createSpecificFieldNode(null, + createIdentifierToken("circuitBreaker"), + createToken(COLON_TOKEN), circuitBreakerValExp); + argumentsList.add(circuitBreakerField); + argumentsList.add(comma); + + // create retryConfig field + ExpressionNode retryConfigValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("retryConfig"))); + SpecificFieldNode retryConfigField = createSpecificFieldNode(null, + createIdentifierToken("retryConfig"), + createToken(COLON_TOKEN), retryConfigValExp); + argumentsList.add(retryConfigField); + argumentsList.add(comma); + + ExpressionNode validationValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(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. *
@@ -669,6 +1066,7 @@ private Node getServiceURLNode(String serviceUrl) {
      * @return {@link VariableDeclarationNode}   Synatx tree node of client initialization
      */
     public VariableDeclarationNode getClientInitializationNode() {
+
         NodeList annotationNodes = createEmptyNodeList();
         // http:Client variable declaration
         BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null,
@@ -686,7 +1084,7 @@ public VariableDeclarationNode getClientInitializationNode() {
         Token comma1 = createIdentifierToken(",");
 
         PositionalArgumentNode positionalArgumentNode02 = createPositionalArgumentNode(createSimpleNameReferenceNode(
-                createIdentifierToken(CONFIG_RECORD_ARG)));
+                createIdentifierToken(HTTP_CLIENT_CONFIG)));
         argumentsList.add(comma1);
         argumentsList.add(positionalArgumentNode02);
 
@@ -709,6 +1107,7 @@ null, typedBindingPatternNode, createToken(EQUAL_TOKEN), initializer,
      * @return {@link AssignmentStatementNode} syntax tree assignment statement node.
      */
     public AssignmentStatementNode getApiKeyAssignmentNode() {
+
         if (apiKey) {
             FieldAccessExpressionNode varRefApiKey = createFieldAccessExpressionNode(
                     createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN),
@@ -731,7 +1130,7 @@ fieldAccessExpressionNode, createToken(DOT_TOKEN),
      *     # Configurations related to client authentication
      *     http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig auth;
      *     # The HTTP version understood by the client
-     *     string httpVersion = "1.1";
+     *     http:HttpVersion httpVersion = http:HTTP_1_1;
      *     # Configurations related to HTTP/1.x protocol
      *     http:ClientHttp1Settings http1Settings = {};
      *     # Configurations related to HTTP/2 protocol
@@ -758,35 +1157,52 @@ fieldAccessExpressionNode, createToken(DOT_TOKEN),
      *     http:ResponseLimitConfigs responseLimits = {};
      *     #SSL/TLS-related options
      *     http:ClientSecureSocket? secureSocket = ();
+     *     # Proxy server related options
+     *     ProxyConfig? proxy = ();
+     *     # Enables the inbound payload validation functionality which provided by the constraint package.
+     *     Enabled by default
+     *     boolean validation = true;
      * 
* * @return {@link List} ClientConfig record fields' node list */ private List getClientConfigRecordFields() { + List recordFieldNodes = new ArrayList<>(); Token semicolonToken = createToken(SEMICOLON_TOKEN); Token equalToken = createToken(EQUAL_TOKEN); - ExpressionNode emptyExpression = createMappingConstructorExpressionNode(createToken(OPEN_BRACE_TOKEN), - createSeparatedNodeList(), createToken(CLOSE_BRACE_TOKEN)); - NilLiteralNode nilLiteralNode = - createNilLiteralNode(createToken(OPEN_PAREN_TOKEN), createToken(CLOSE_PAREN_TOKEN)); + Token questionMarkToken = createToken(QUESTION_MARK_TOKEN); // add auth field - 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); + if (isHttpOROAuth() && !isApiKey()) { + 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() && isApiKey()) { + MetadataNode authMetadataNode = getMetadataNode( + "Provides Auth configurations needed when communicating with a remote HTTP endpoint."); + IdentifierToken authFieldName = AbstractNodeFactory.createIdentifierToken(escapeIdentifier( + AUTH)); + TypeDescriptorNode unionTypeDesctiptor = createUnionTypeDescriptorNode( + createSimpleNameReferenceNode(createIdentifierToken(getAuthFieldTypeName())), + createToken(PIPE_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(API_KEYS_CONFIG))); + RecordFieldNode authFieldNode = NodeFactory.createRecordFieldNode(authMetadataNode, null, + unionTypeDesctiptor, authFieldName, null, semicolonToken); + recordFieldNodes.add(authFieldNode); + } // add httpVersion field MetadataNode httpVersionMetadata = getMetadataNode("The HTTP version understood by the client"); - TypeDescriptorNode httpVersionFieldType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + TypeDescriptorNode httpVersionFieldType = createSimpleNameReferenceNode(createIdentifierToken(HTTP_VERSION)); IdentifierToken httpVersionFieldName = createIdentifierToken("httpVersion"); RequiredExpressionNode httpVersionExpression = - createRequiredExpressionNode(createIdentifierToken("\"1.1\"")); + createRequiredExpressionNode(createIdentifierToken(this.httpVersion)); RecordFieldWithDefaultValueNode httpVersionFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( httpVersionMetadata, null, httpVersionFieldType, httpVersionFieldName, equalToken, httpVersionExpression, semicolonToken); @@ -796,10 +1212,9 @@ private List getClientConfigRecordFields() { MetadataNode http1SettingsMetadata = getMetadataNode("Configurations related to HTTP/1.x protocol"); IdentifierToken http1SettingsFieldName = createIdentifierToken("http1Settings"); TypeDescriptorNode http1SettingsFieldType = - createSimpleNameReferenceNode(createIdentifierToken("http:ClientHttp1Settings")); - RecordFieldWithDefaultValueNode http1SettingsFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( - http1SettingsMetadata, null, http1SettingsFieldType, http1SettingsFieldName, - equalToken, emptyExpression, semicolonToken); + createSimpleNameReferenceNode(createIdentifierToken("ClientHttp1Settings")); + RecordFieldNode http1SettingsFieldNode = createRecordFieldNode(http1SettingsMetadata, null, + http1SettingsFieldType, http1SettingsFieldName, questionMarkToken, semicolonToken); recordFieldNodes.add(http1SettingsFieldNode); // add http2Settings fields @@ -807,9 +1222,9 @@ private List getClientConfigRecordFields() { TypeDescriptorNode http2SettingsFieldType = createSimpleNameReferenceNode(createIdentifierToken("http:ClientHttp2Settings")); IdentifierToken http2SettingsFieldName = createIdentifierToken("http2Settings"); - RecordFieldWithDefaultValueNode http2SettingsFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + RecordFieldNode http2SettingsFieldNode = NodeFactory.createRecordFieldNode( http2SettingsMetadata, null, http2SettingsFieldType, http2SettingsFieldName, - equalToken, emptyExpression, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(http2SettingsFieldNode); // add timeout field @@ -834,24 +1249,14 @@ private List getClientConfigRecordFields() { equalToken, forwardedDefaultValue, semicolonToken); recordFieldNodes.add(forwardedFieldNode); - // add followRedirects field - MetadataNode followRedirectsMetadata = getMetadataNode("Configurations associated with Redirection"); - IdentifierToken followRedirectsFieldName = AbstractNodeFactory.createIdentifierToken("followRedirects"); - TypeDescriptorNode followRedirectsFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:FollowRedirects"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode followRedirectsFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( - followRedirectsMetadata, null, followRedirectsFieldType, - followRedirectsFieldName, equalToken, nilLiteralNode, semicolonToken); - recordFieldNodes.add(followRedirectsFieldNode); - // add poolConfig field MetadataNode poolConfigMetaData = getMetadataNode("Configurations associated with request pooling"); IdentifierToken poolConfigFieldName = AbstractNodeFactory.createIdentifierToken("poolConfig"); - TypeDescriptorNode poolConfigFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:PoolConfiguration"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode poolConfigFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + TypeDescriptorNode poolConfigFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:PoolConfiguration")); + RecordFieldNode poolConfigFieldNode = NodeFactory.createRecordFieldNode( poolConfigMetaData, null, poolConfigFieldType, poolConfigFieldName, - equalToken, nilLiteralNode, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(poolConfigFieldNode); // add cache field @@ -859,9 +1264,9 @@ private List getClientConfigRecordFields() { IdentifierToken cacheFieldName = createIdentifierToken("cache"); TypeDescriptorNode cacheFieldType = createSimpleNameReferenceNode(createIdentifierToken("http:CacheConfig")); - RecordFieldWithDefaultValueNode cachFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + RecordFieldNode cachFieldNode = NodeFactory.createRecordFieldNode( cachMetadata, null, cacheFieldType, cacheFieldName, - equalToken, emptyExpression, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(cachFieldNode); // add compression field @@ -881,64 +1286,63 @@ private List getClientConfigRecordFields() { MetadataNode circuitBreakerMetadata = getMetadataNode( "Configurations associated with the behaviour of the Circuit Breaker"); IdentifierToken circuitBreakerFieldName = AbstractNodeFactory.createIdentifierToken("circuitBreaker"); - TypeDescriptorNode circuitBreakerFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:CircuitBreakerConfig"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode circuitBreakerFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + TypeDescriptorNode circuitBreakerFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:CircuitBreakerConfig")); + RecordFieldNode circuitBreakerFieldNode = NodeFactory.createRecordFieldNode( circuitBreakerMetadata, null, circuitBreakerFieldType, circuitBreakerFieldName, - equalToken, nilLiteralNode, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(circuitBreakerFieldNode); // add retryConfig field MetadataNode retryConfigMetadata = getMetadataNode("Configurations associated with retrying"); IdentifierToken retryConfigFieldName = AbstractNodeFactory.createIdentifierToken("retryConfig"); - TypeDescriptorNode returConfigFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:RetryConfig"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode retryConfigFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + TypeDescriptorNode returConfigFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:RetryConfig")); + RecordFieldNode retryConfigFieldNode = NodeFactory.createRecordFieldNode( retryConfigMetadata, null, returConfigFieldType, retryConfigFieldName, - equalToken, nilLiteralNode, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(retryConfigFieldNode); - // add cookieConfig field - MetadataNode cookieConfigMetadata = getMetadataNode("Configurations associated with cookies"); - IdentifierToken cookieConfigFieldName = AbstractNodeFactory.createIdentifierToken("cookieConfig"); - TypeDescriptorNode cookieConfigFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:CookieConfig"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode cookieConfigFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( - cookieConfigMetadata, null, cookieConfigFieldType, cookieConfigFieldName, - equalToken, nilLiteralNode, semicolonToken); - recordFieldNodes.add(cookieConfigFieldNode); - // add responseLimits field MetadataNode responseLimitsMetadata = getMetadataNode( "Configurations associated with inbound response size limits"); IdentifierToken responseLimitsFieldName = createIdentifierToken("responseLimits"); TypeDescriptorNode responseLimitsFieldType = createSimpleNameReferenceNode( createIdentifierToken("http:ResponseLimitConfigs")); - RecordFieldWithDefaultValueNode responseLimitsFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + RecordFieldNode responseLimitsFieldNode = NodeFactory.createRecordFieldNode( responseLimitsMetadata, null, responseLimitsFieldType, responseLimitsFieldName, - equalToken, emptyExpression, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(responseLimitsFieldNode); // add secureSocket field MetadataNode secureSocketMetadata = getMetadataNode("SSL/TLS-related options"); IdentifierToken secureSocketFieldName = AbstractNodeFactory.createIdentifierToken(SSL_FIELD_NAME); - TypeDescriptorNode secureSocketfieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:ClientSecureSocket"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode secureSocketFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + TypeDescriptorNode secureSocketfieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:ClientSecureSocket")); + RecordFieldNode secureSocketFieldNode = NodeFactory.createRecordFieldNode( secureSocketMetadata, null, secureSocketfieldType, secureSocketFieldName, - equalToken, nilLiteralNode, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(secureSocketFieldNode); // add proxy server field MetadataNode proxyConfigMetadata = getMetadataNode("Proxy server related options"); IdentifierToken proxyConfigFieldName = AbstractNodeFactory.createIdentifierToken(PROXY_CONFIG); - TypeDescriptorNode proxyConfigFieldType = createOptionalTypeDescriptorNode( - createIdentifierToken("http:ProxyConfig"), createToken(QUESTION_MARK_TOKEN)); - RecordFieldWithDefaultValueNode proxyConfigFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + TypeDescriptorNode proxyConfigFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:ProxyConfig")); + RecordFieldNode proxyConfigFieldNode = NodeFactory.createRecordFieldNode( proxyConfigMetadata, null, proxyConfigFieldType, proxyConfigFieldName, - equalToken, nilLiteralNode, semicolonToken); + questionMarkToken, semicolonToken); recordFieldNodes.add(proxyConfigFieldNode); + // add validation for constraint + MetadataNode validationMetadata = getMetadataNode("Enables the inbound payload validation " + + "functionality which provided by the constraint package. Enabled by default"); + 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; } @@ -946,25 +1350,24 @@ private List getClientConfigRecordFields() { * Generate statements for init function when combination of ApiKeys and HTTP/OAuth authentication is used. * *
-     *     if authConfig.auth is ApiKeysConfig {
-     *         self.apiKeyConfig = (authConfig.auth).cloneReadOnly();
+     *     if config.auth is ApiKeysConfig {
+     *         self.apiKeyConfig = (config.auth).cloneReadOnly();
      *     } else {
-     *         clientConfig.auth = http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig>authConfig.auth;
+     *         config.auth = config.auth;
      *         self.apiKeyConfig = ();
      *     }
      * 
* - * @param assignmentNodes List of Assignment Nodes */ - public void handleInitForMixOfApiKeyAndHTTPOrOAuth(List assignmentNodes) { + public IfElseStatementNode handleInitForMixOfApiKeyAndHTTPOrOAuth() { List apiKeyConfigAssignmentNodes = new ArrayList<>(); - // `self.apiKeyConfig = (authConfig.auth).cloneReadOnly();` + // `self.apiKeyConfig = (config.auth).cloneReadOnly();` FieldAccessExpressionNode apiKeyConfigRef = createFieldAccessExpressionNode( createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG_PARAM))); SimpleNameReferenceNode apiKeyConfigExpr = createSimpleNameReferenceNode(createIdentifierToken( - "(authConfig.auth).cloneReadOnly()")); + "(config.auth).cloneReadOnly()")); AssignmentStatementNode apiKeyConfigAssignmentStatementNode = createAssignmentStatementNode(apiKeyConfigRef, createToken(EQUAL_TOKEN), apiKeyConfigExpr, createToken(SEMICOLON_TOKEN)); apiKeyConfigAssignmentNodes.add(apiKeyConfigAssignmentStatementNode); @@ -974,13 +1377,13 @@ public void handleInitForMixOfApiKeyAndHTTPOrOAuth(List assignmen List clientConfigAssignmentNodes = new ArrayList<>(); - // `clientConfig.auth = authConfig.auth; + // config.auth = config.auth; FieldAccessExpressionNode clientConfigAuthRef = createFieldAccessExpressionNode( - createSimpleNameReferenceNode(createIdentifierToken(CONFIG_RECORD_ARG)), createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(CONFIG)), createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(AUTH))); SimpleNameReferenceNode clientConfigExpr = createSimpleNameReferenceNode( createIdentifierToken("<" + getAuthFieldTypeName() + - ">" + AUTH_CONFIG + DOT_TOKEN.stringValue() + AUTH)); + ">" + CONFIG + DOT_TOKEN.stringValue() + AUTH)); AssignmentStatementNode httpClientAuthConfigAssignment = createAssignmentStatementNode(clientConfigAuthRef, createToken(EQUAL_TOKEN), clientConfigExpr, createToken(SEMICOLON_TOKEN)); clientConfigAssignmentNodes.add(httpClientAuthConfigAssignment); @@ -1001,54 +1404,184 @@ public void handleInitForMixOfApiKeyAndHTTPOrOAuth(List assignmen ElseBlockNode elseBody = createElseBlockNode(createToken(ELSE_KEYWORD), elseBodyStatement); ExpressionNode condition = createBinaryExpressionNode(null, - createIdentifierToken(AUTH_CONFIG + DOT_TOKEN.stringValue() + AUTH), + createIdentifierToken(CONFIG + DOT_TOKEN.stringValue() + AUTH), createToken(IS_KEYWORD), createIdentifierToken(API_KEYS_CONFIG) ); - IfElseStatementNode ifElseStatementNode = createIfElseStatementNode(createToken(IF_KEYWORD), condition, + return createIfElseStatementNode(createToken(IF_KEYWORD), condition, ifBody, elseBody); - assignmentNodes.add(ifElseStatementNode); } - /** - * Generate fields for`AuthConfig` record when combination of ApiKey and HTTPOrOAuth authentication is supported. - * - *
-     *     # Auth Configuration
-     *     http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig|ApiKeysConfig auth;
-     * 
- * - * @return {@link List} fields of AuthConfig record - */ - private List getAuthConfigRecordFields() { + private List getCustomProxyRecordFields() { + List recordFieldNodes = new ArrayList<>(); + Token semicolonToken = createToken(SEMICOLON_TOKEN); + + MetadataNode hostMetadataNode = getMetadataNode("Host name of the proxy server"); + IdentifierToken hostFieldName = createIdentifierToken(escapeIdentifier("host")); + TypeDescriptorNode hostFieldType = createSimpleNameReferenceNode(createIdentifierToken(STRING)); + ExpressionNode hostDefaultValue = createRequiredExpressionNode( + createIdentifierToken("\"\"")); + RecordFieldWithDefaultValueNode hostRecordField = createRecordFieldWithDefaultValueNode(hostMetadataNode, + null, hostFieldType, hostFieldName, createToken(EQUAL_TOKEN), + hostDefaultValue, semicolonToken); + recordFieldNodes.add(hostRecordField); + + MetadataNode proxyMetadataNode = getMetadataNode("Proxy server port"); + IdentifierToken proxyFieldName = createIdentifierToken(escapeIdentifier("port")); + TypeDescriptorNode proxyFieldType = createSimpleNameReferenceNode(createIdentifierToken("int")); + ExpressionNode proxyDefaultValue = createRequiredExpressionNode( + createIdentifierToken("0")); + RecordFieldWithDefaultValueNode proxyRecordField = createRecordFieldWithDefaultValueNode(proxyMetadataNode, + null, proxyFieldType, proxyFieldName, createToken(EQUAL_TOKEN), + proxyDefaultValue, semicolonToken); + recordFieldNodes.add(proxyRecordField); + + MetadataNode usernameMetadataNode = getMetadataNode("Proxy server username"); + IdentifierToken usernameFieldName = createIdentifierToken(escapeIdentifier("userName")); + TypeDescriptorNode usernameFieldType = createSimpleNameReferenceNode(createIdentifierToken(STRING)); + ExpressionNode usernameDefaultValue = createRequiredExpressionNode( + createIdentifierToken("\"\"")); + RecordFieldWithDefaultValueNode usernameRecordField = createRecordFieldWithDefaultValueNode( + usernameMetadataNode, null, usernameFieldType, usernameFieldName, + createToken(EQUAL_TOKEN), + usernameDefaultValue, semicolonToken); + recordFieldNodes.add(usernameRecordField); + + List annotationNodes = Collections.singletonList(getDisplayAnnotationForPasswordField()); + + MetadataNode passwordMetadataNode = getMetadataNode("Proxy server password", annotationNodes); + IdentifierToken passwordFieldName = createIdentifierToken(escapeIdentifier("password")); + TypeDescriptorNode passwordFieldType = createSimpleNameReferenceNode(createIdentifierToken(STRING)); + ExpressionNode passwordDefaultValue = createRequiredExpressionNode( + createIdentifierToken("\"\"")); + RecordFieldWithDefaultValueNode passwordRecordField = createRecordFieldWithDefaultValueNode( + passwordMetadataNode, null, passwordFieldType, passwordFieldName, + createToken(EQUAL_TOKEN), + passwordDefaultValue, semicolonToken); + recordFieldNodes.add(passwordRecordField); + + return recordFieldNodes; + } + + private AnnotationNode getDisplayAnnotationForRecord(String label) { + List annotFields = new ArrayList<>(); + BasicLiteralNode labelExpr = createBasicLiteralNode(STRING_LITERAL, + createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, + "\"" + label + "\"", + createEmptyMinutiaeList(), + createEmptyMinutiaeList())); + SpecificFieldNode labelField = createSpecificFieldNode(null, + createIdentifierToken("label"), + createToken(COLON_TOKEN), labelExpr); + annotFields.add(labelField); + MappingConstructorExpressionNode annotValue = createMappingConstructorExpressionNode( + createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(annotFields), + createToken(CLOSE_BRACE_TOKEN)); + + SimpleNameReferenceNode annotateReference = + createSimpleNameReferenceNode(createIdentifierToken("display")); + + return createAnnotationNode(createToken(SyntaxKind.AT_TOKEN) + , annotateReference, annotValue); + } + + private AnnotationNode getDisplayAnnotationForPasswordField() { + List annotFields = new ArrayList<>(); + BasicLiteralNode labelExpr = createBasicLiteralNode(STRING_LITERAL, + createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, + "\"\"", + createEmptyMinutiaeList(), + createEmptyMinutiaeList())); + SpecificFieldNode labelField = createSpecificFieldNode(null, + createIdentifierToken("label"), + createToken(COLON_TOKEN), labelExpr); + annotFields.add(labelField); + annotFields.add(createToken(COMMA_TOKEN)); + BasicLiteralNode kindExpr = createBasicLiteralNode(STRING_LITERAL, + createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, + "\"password\"", + createEmptyMinutiaeList(), + createEmptyMinutiaeList())); + SpecificFieldNode kindField = createSpecificFieldNode(null, + createIdentifierToken("kind"), + createToken(COLON_TOKEN), kindExpr); + annotFields.add(kindField); + + MappingConstructorExpressionNode annotValue = createMappingConstructorExpressionNode( + createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(annotFields), + createToken(CLOSE_BRACE_TOKEN)); + + SimpleNameReferenceNode annotateReference = + createSimpleNameReferenceNode(createIdentifierToken("display")); + + return createAnnotationNode(createToken(SyntaxKind.AT_TOKEN) + , annotateReference, annotValue); + } + + private List getClientHttp1SettingsRecordFields() { List recordFieldNodes = new ArrayList<>(); Token semicolonToken = createToken(SEMICOLON_TOKEN); - MetadataNode authMetadataNode = getMetadataNode("Auth Configuration"); - IdentifierToken authFieldName = AbstractNodeFactory.createIdentifierToken(escapeIdentifier(AUTH)); - TypeDescriptorNode authFieldTypeNode = createSimpleNameReferenceNode( - createIdentifierToken(getAuthFieldTypeName() + "|" + API_KEYS_CONFIG)); - RecordFieldNode authFieldNode = NodeFactory.createRecordFieldNode(authMetadataNode, null, - authFieldTypeNode, authFieldName, null, semicolonToken); - recordFieldNodes.add(authFieldNode); + MetadataNode keepAliveMetadataNode = getMetadataNode( + "Specifies whether to reuse a connection for multiple requests"); + IdentifierToken keepAliveFieldName = createIdentifierToken(escapeIdentifier(KEEP_ALIVE)); + TypeDescriptorNode keepAliveFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:KeepAlive")); + ExpressionNode keepAliveDefaultValue = createRequiredExpressionNode( + createIdentifierToken("http:KEEPALIVE_AUTO")); + RecordFieldWithDefaultValueNode keepAliveRecordField = createRecordFieldWithDefaultValueNode( + keepAliveMetadataNode, null, keepAliveFieldType, keepAliveFieldName, + createToken(EQUAL_TOKEN), keepAliveDefaultValue, semicolonToken); + recordFieldNodes.add(keepAliveRecordField); + + MetadataNode chunkingMetadataNode = getMetadataNode("The chunking behaviour of the request"); + IdentifierToken chunkingFieldName = createIdentifierToken(escapeIdentifier(CHUNKING)); + TypeDescriptorNode chunkingFieldType = createSimpleNameReferenceNode( + createIdentifierToken("http:Chunking")); + ExpressionNode chunkingDefaultValue = createRequiredExpressionNode( + createIdentifierToken("http:CHUNKING_AUTO")); + RecordFieldWithDefaultValueNode chunkingRecordField = createRecordFieldWithDefaultValueNode( + chunkingMetadataNode, null, chunkingFieldType, chunkingFieldName, + createToken(EQUAL_TOKEN), chunkingDefaultValue, semicolonToken); + recordFieldNodes.add(chunkingRecordField); + + MetadataNode proxyMetadataNode = getMetadataNode("Proxy server related options"); + IdentifierToken proxyFieldName = AbstractNodeFactory.createIdentifierToken(PROXY_CONFIG); + TypeDescriptorNode proxyFieldType = createSimpleNameReferenceNode( + createIdentifierToken("ProxyConfig")); + RecordFieldNode proxyRecordField = NodeFactory.createRecordFieldNode( + proxyMetadataNode, null, proxyFieldType, proxyFieldName, + createToken(QUESTION_MARK_TOKEN), semicolonToken); + recordFieldNodes.add(proxyRecordField); + return recordFieldNodes; + } private MetadataNode getMetadataNode(String comment) { + List docs = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc(comment, false)); MarkdownDocumentationNode authDocumentationNode = createMarkdownDocumentationNode( createNodeList(docs)); return createMetadataNode(authDocumentationNode, createEmptyNodeList()); } + private MetadataNode getMetadataNode(String comment, List annotationNodes) { + List docs = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc(comment, false)); + MarkdownDocumentationNode authDocumentationNode = createMarkdownDocumentationNode( + createNodeList(docs)); + return createMetadataNode(authDocumentationNode, createNodeList(annotationNodes)); + } + /** * Travers through the security schemas of the given open 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 open api spec + * @param securitySchemeMap Map of security schemas of the given open api spec */ - private void setAuthTypes(Map securitySchemeMap) throws + public void setAuthTypes(Map securitySchemeMap) throws BallerinaOpenApiException { + for (Map.Entry securitySchemeEntry : securitySchemeMap.entrySet()) { SecurityScheme schemaValue = securitySchemeEntry.getValue(); if (schemaValue != null && schemaValue.getType() != null) { @@ -1117,12 +1650,13 @@ private void setAuthTypes(Map securitySchemeMap) throws * # API key related to connector authentication * string apiKey; *
- * */ private void setApiKeysConfigRecordFields(SecurityScheme securityScheme) { + MetadataNode metadataNode = null; if (securityScheme.getDescription() != null) { - metadataNode = getMetadataNode(securityScheme.getDescription()); + List annotationNodes = Collections.singletonList(getDisplayAnnotationForPasswordField()); + metadataNode = getMetadataNode(securityScheme.getDescription(), annotationNodes); } TypeDescriptorNode stringTypeDesc = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); IdentifierToken apiKeyName = createIdentifierToken(getValidName(securityScheme.getName(), false)); @@ -1134,17 +1668,17 @@ private void setApiKeysConfigRecordFields(SecurityScheme securityScheme) { * 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} + * Ex: {@code http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig} */ - public String getAuthFieldTypeName() { + private String getAuthFieldTypeName() { Set httpFieldTypeNames = new HashSet<>(); for (String authType : authTypes) { switch (authType) { case BEARER: - httpFieldTypeNames.add(AuthConfigTypes.BEARER.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.BEARER.getValue()); break; case BASIC: - httpFieldTypeNames.add(AuthConfigTypes.BASIC.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.BASIC.getValue()); break; case CLIENT_CRED: // Previous version of swagger parser returns null value, when it has an @@ -1152,23 +1686,23 @@ public String getAuthFieldTypeName() { // 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(AuthConfigTypes.CUSTOM_CLIENT_CREDENTIAL.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_CLIENT_CREDENTIAL.getValue()); } else { - httpFieldTypeNames.add(AuthConfigTypes.CLIENT_CREDENTIAL.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CLIENT_CREDENTIAL.getValue()); } break; case PASSWORD: if (passwordGrantTokenUrl != null && !passwordGrantTokenUrl.isBlank()) { - httpFieldTypeNames.add(AuthConfigTypes.CUSTOM_PASSWORD.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_PASSWORD.getValue()); } else { - httpFieldTypeNames.add(AuthConfigTypes.PASSWORD.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.PASSWORD.getValue()); } break; case REFRESH_TOKEN: if (refreshTokenUrl != null && !refreshTokenUrl.isBlank()) { - httpFieldTypeNames.add(AuthConfigTypes.CUSTOM_REFRESH_TOKEN.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_REFRESH_TOKEN.getValue()); } else { - httpFieldTypeNames.add(AuthConfigTypes.REFRESH_TOKEN.getValue()); + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.REFRESH_TOKEN.getValue()); } break; default: @@ -1181,7 +1715,7 @@ public String getAuthFieldTypeName() { /** * This method is used concat the config record authConfig field type. * - * @param fieldtypes Type name set from {@link #setAuthTypes(Map)} method. + * @param fieldtypes Type name set from {@link #setAuthTypes(Map)} method. * @return {@link String} Pipe concatenated list of type names */ private StringBuilder buildConfigRecordFieldTypes(Set fieldtypes) { diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaClientGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaClientGenerator.java similarity index 87% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaClientGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaClientGenerator.java index 9b1bb6477..f34a83f4d 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaClientGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaClientGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client; +package io.ballerina.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; @@ -48,13 +48,13 @@ 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.VariableDeclarationNode; -import io.ballerina.openapi.cmd.Filter; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.DocCommentsGenerator; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.model.OASClientConfig; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.model.Filter; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; import io.swagger.v3.oas.models.OpenAPI; @@ -67,6 +67,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -114,15 +115,18 @@ 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.openapi.generators.GeneratorConstants.DEFAULT_API_KEY_DESC; -import static io.ballerina.openapi.generators.GeneratorConstants.HTTP; -import static io.ballerina.openapi.generators.GeneratorConstants.SELF; -import static io.ballerina.openapi.generators.GeneratorConstants.X_BALLERINA_INIT_DESCRIPTION; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_API_KEY_DESC; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP; +import static io.ballerina.openapi.core.GeneratorConstants.SELF; +import static io.ballerina.openapi.core.GeneratorConstants.X_BALLERINA_INIT_DESCRIPTION; /** * This class is used to generate ballerina client file according to given yaml file. + * + * @since 1.3.0 */ public class BallerinaClientGenerator { + private final Filter filters; private List imports; private List typeDefinitionNodeList; @@ -147,6 +151,7 @@ public List getTypeDefinitionNodeList() { * Returns ballerinaAuthConfigGenerator. */ public BallerinaAuthConfigGenerator getBallerinaAuthConfigGenerator() { + return ballerinaAuthConfigGenerator; } @@ -158,47 +163,52 @@ public void setTypeDefinitionNodeList( this.typeDefinitionNodeList = typeDefinitionNodeList; } - public List getRemoteFunctionNameList () { + + public List getRemoteFunctionNameList() { + return remoteFunctionNameList; } /** * Returns server URL. + * * @return {@link String} */ - public String getServerUrl () { + public String getServerUrl() { + return serverURL; } - public BallerinaClientGenerator(OpenAPI openAPI, Filter filters, boolean nullable, boolean resourceMode) { + public BallerinaClientGenerator(OASClientConfig oasClientConfig) { - this.filters = filters; + this.filters = oasClientConfig.getFilters(); this.imports = new ArrayList<>(); this.typeDefinitionNodeList = new ArrayList<>(); - this.openAPI = openAPI; - this.ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, nullable); + this.openAPI = oasClientConfig.getOpenAPI(); + this.ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, + oasClientConfig.isNullable(), new LinkedList<>()); this.ballerinaUtilGenerator = new BallerinaUtilGenerator(); this.remoteFunctionNameList = new ArrayList<>(); this.serverURL = "/"; this.ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(false, false); - this.resourceMode = resourceMode; + this.resourceMode = oasClientConfig.isResourceMode(); } /** * This method for generate the client syntax tree. * - * @return return Syntax tree for the ballerina code. - * @throws BallerinaOpenApiException When function fail in process. + * @return return Syntax tree for the ballerina code. + * @throws BallerinaOpenApiException When function fail in process. */ public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { // Create `ballerina/http` import declaration node ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA - , GeneratorConstants.HTTP); + , HTTP); imports.add(importForHttp); - List nodes = new ArrayList<>(); + List nodes = new ArrayList<>(); // Add authentication related records - ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI, nodes); + ballerinaAuthConfigGenerator.addAuthRelatedRecords(openAPI); // Add class definition node to module member nodes nodes.add(getClassDefinitionNode()); @@ -212,6 +222,7 @@ public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { } public BallerinaUtilGenerator getBallerinaUtilGenerator() { + return ballerinaUtilGenerator; } @@ -220,7 +231,7 @@ public BallerinaUtilGenerator getBallerinaUtilGenerator() { *
      *     public isolated client class Client {
      *     final http:Client clientEp;
-     *     public isolated function init(http:ClientConfiguration clientConfig =  {}, string serviceUrl = "/url")
+     *     public isolated function init(ConnectionConfig config =  {}, string serviceUrl = "/url")
      *     returns error? {
      *         http:Client httpEp = check new (serviceUrl, clientConfig);
      *         self.clientEp = httpEp;
@@ -234,9 +245,9 @@ public BallerinaUtilGenerator getBallerinaUtilGenerator() {
      * }
      * 
*/ - private ClassDefinitionNode getClassDefinitionNode() throws BallerinaOpenApiException { + private ClassDefinitionNode getClassDefinitionNode() throws BallerinaOpenApiException { // Collect members for class definition node - List memberNodeList = new ArrayList<>(); + List memberNodeList = new ArrayList<>(); // Add instance variable to class definition node memberNodeList.addAll(createClassInstanceVariables()); // Add init function to class definition node @@ -249,18 +260,19 @@ private ClassDefinitionNode getClassDefinitionNode() throws BallerinaOpenApiExc NodeList classTypeQualifiers = createNodeList( createToken(ISOLATED_KEYWORD), createToken(CLIENT_KEYWORD)); return createClassDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), classTypeQualifiers, - createToken(CLASS_KEYWORD), className, createToken(OPEN_BRACE_TOKEN), - createNodeList(memberNodeList), createToken(CLOSE_BRACE_TOKEN)); + createToken(CLASS_KEYWORD), className, createToken(OPEN_BRACE_TOKEN), + createNodeList(memberNodeList), createToken(CLOSE_BRACE_TOKEN), null); } /** * Generate metadata node of the class including documentation and display annotation. Content of the documentation * will be taken from the `description` section inside the `info` section in OpenAPI definition. * - * @return {@link MetadataNode} Metadata node of the client class + * @return {@link MetadataNode} Metadata node of the client class */ private MetadataNode getClassMetadataNode() { - List classLevelAnnotationNodes = new ArrayList<>(); + + List classLevelAnnotationNodes = new ArrayList<>(); if (openAPI.getInfo().getExtensions() != null) { Map extensions = openAPI.getInfo().getExtensions(); DocCommentsGenerator.extractDisplayAnnotation(extensions, classLevelAnnotationNodes); @@ -280,7 +292,7 @@ private MetadataNode getClassMetadataNode() { * -- Scenario 1: init function when authentication mechanism is API key *
      *   public isolated function init(ApiKeysConfig apiKeyConfig, string serviceUrl,
-     *      http:ClientConfiguration clientConfig =  {}) returns error? {
+     *     ConnectionConfig config =  {}) returns error? {
      *         http:Client httpEp = check new (serviceUrl, clientConfig);
      *         self.clientEp = httpEp;
      *         self.apiKeys = apiKeyConfig.apiKeys.cloneReadOnly();
@@ -295,7 +307,7 @@ private MetadataNode getClassMetadataNode() {
      * 
* -- Scenario 3: init function when no authentication mechanism is provided *
-     *   public isolated function init(http:ClientConfiguration clientConfig =  {},
+     *   public isolated function init(ConnectionConfig config =  {},
      *      string serviceUrl = "base-url") returns error? {
      *         http:Client httpEp = check new (serviceUrl, clientConfig);
      *         self.clientEp = httpEp;
@@ -303,9 +315,10 @@ private MetadataNode getClassMetadataNode() {
      * 
* * @return {@link FunctionDefinitionNode} Class init function - * @throws BallerinaOpenApiException When invalid server URL is provided + * @throws BallerinaOpenApiException When invalid server URL is provided */ private FunctionDefinitionNode createInitFunction() throws BallerinaOpenApiException { + FunctionSignatureNode functionSignatureNode = getInitFunctionSignatureNode(); FunctionBodyNode functionBodyNode = getInitFunctionBodyNode(); NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); @@ -317,18 +330,22 @@ private FunctionDefinitionNode createInitFunction() throws BallerinaOpenApiExcep /** * Create function body node of client init function. * - * @return {@link FunctionBodyNode} + * @return {@link FunctionBodyNode} */ private FunctionBodyNode getInitFunctionBodyNode() { + List assignmentNodes = new ArrayList<>(); + assignmentNodes.add(ballerinaAuthConfigGenerator.getHttpClientConfigVariableNode()); + assignmentNodes.add(ballerinaAuthConfigGenerator.getClientConfigDoStatementNode()); + // If both apiKey and httpOrOAuth is supported + // todo : After revamping if (ballerinaAuthConfigGenerator.isApiKey() && ballerinaAuthConfigGenerator.isHttpOROAuth()) { - ballerinaAuthConfigGenerator.handleInitForMixOfApiKeyAndHTTPOrOAuth(assignmentNodes); + assignmentNodes.add(ballerinaAuthConfigGenerator.handleInitForMixOfApiKeyAndHTTPOrOAuth()); } - // create initialization statement of http:Client class instance - VariableDeclarationNode clientInitializationNode = ballerinaAuthConfigGenerator.getClientInitializationNode(); + assignmentNodes.add(ballerinaAuthConfigGenerator.getClientInitializationNode()); // create {@code self.clientEp = httpEp;} assignment node FieldAccessExpressionNode varRef = createFieldAccessExpressionNode( createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), @@ -336,9 +353,9 @@ private FunctionBodyNode getInitFunctionBodyNode() { SimpleNameReferenceNode expr = createSimpleNameReferenceNode(createIdentifierToken("httpEp")); AssignmentStatementNode httpClientAssignmentStatementNode = createAssignmentStatementNode(varRef, createToken(EQUAL_TOKEN), expr, createToken(SEMICOLON_TOKEN)); - - assignmentNodes.add(clientInitializationNode); assignmentNodes.add(httpClientAssignmentStatementNode); + + // Get API key assignment node if authentication mechanism type is only `apiKey` if (ballerinaAuthConfigGenerator.isApiKey() && !ballerinaAuthConfigGenerator.isHttpOROAuth()) { assignmentNodes.add(ballerinaAuthConfigGenerator.getApiKeyAssignmentNode()); @@ -354,16 +371,17 @@ private FunctionBodyNode getInitFunctionBodyNode() { assignmentNodes.add(returnStatementNode); NodeList statementList = createNodeList(assignmentNodes); return createFunctionBodyBlockNode(createToken(OPEN_BRACE_TOKEN), - null, statementList, createToken(CLOSE_BRACE_TOKEN)); + null, statementList, createToken(CLOSE_BRACE_TOKEN), null); } /** * Create function signature node of client init function. * - * @return {@link FunctionSignatureNode} - * @throws BallerinaOpenApiException When invalid server URL is provided + * @return {@link FunctionSignatureNode} + * @throws BallerinaOpenApiException When invalid server URL is provided */ private FunctionSignatureNode getInitFunctionSignatureNode() throws BallerinaOpenApiException { + serverURL = getServerURL(openAPI.getServers()); SeparatedNodeList parameterList = createSeparatedNodeList( ballerinaAuthConfigGenerator.getConfigParamForClassInit(serverURL)); @@ -377,14 +395,16 @@ private FunctionSignatureNode getInitFunctionSignatureNode() throws BallerinaOpe /** * Provide client class init function's documentation including function description and parameter descriptions. - * @return {@link MetadataNode} Metadata node containing entire function documentation comment. + * + * @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"; if (openAPI.getInfo().getExtensions() != null && !openAPI.getInfo().getExtensions().isEmpty()) { Map extensions = openAPI.getInfo().getExtensions(); - for (Map.Entry extension: extensions.entrySet()) { + for (Map.Entry extension : extensions.entrySet()) { if (extension.getKey().trim().equals(X_BALLERINA_INIT_DESCRIPTION)) { clientInitDocComment = clientInitDocComment.concat(extension.getValue().toString()); break; @@ -393,17 +413,13 @@ private MetadataNode getInitDocComment() { } //todo: setInitDocComment() pass the references docs.addAll(DocCommentsGenerator.createAPIDescriptionDoc(clientInitDocComment, true)); - if (ballerinaAuthConfigGenerator.isApiKey() && ballerinaAuthConfigGenerator.isHttpOROAuth()) { - MarkdownParameterDocumentationLineNode authConfig = DocCommentsGenerator.createAPIParamDoc( - "authConfig", "Configurations used for Authentication"); - docs.add(authConfig); - } else if (ballerinaAuthConfigGenerator.isApiKey()) { + if (ballerinaAuthConfigGenerator.isApiKey() && !ballerinaAuthConfigGenerator.isHttpOROAuth()) { MarkdownParameterDocumentationLineNode apiKeyConfig = DocCommentsGenerator.createAPIParamDoc( "apiKeyConfig", DEFAULT_API_KEY_DESC); docs.add(apiKeyConfig); } // Create method description - MarkdownParameterDocumentationLineNode clientConfig = DocCommentsGenerator.createAPIParamDoc("clientConfig", + MarkdownParameterDocumentationLineNode clientConfig = DocCommentsGenerator.createAPIParamDoc("config", "The configurations to be used when initializing the `connector`"); docs.add(clientConfig); MarkdownParameterDocumentationLineNode serviceUrlAPI = DocCommentsGenerator.createAPIParamDoc("serviceUrl", @@ -416,13 +432,13 @@ private MetadataNode getInitDocComment() { return createMetadataNode(clientInitDoc, createEmptyNodeList()); } - /** * Generate client class instance variables. * * @return {@link List} List of instance variables */ private List createClassInstanceVariables() { + List fieldNodeList = new ArrayList<>(); Token finalKeywordToken = createToken(FINAL_KEYWORD); NodeList qualifierList = createNodeList(finalKeywordToken); @@ -441,16 +457,15 @@ private List createClassInstanceVariables() { return fieldNodeList; } - /** * Generate remote functions for OpenAPI operations. * - * @param paths openAPI Paths - * @param filter user given tags and operations - * @return FunctionDefinitionNodes list + * @param paths openAPI Paths + * @param filter user given tags and operations + * @return FunctionDefinitionNodes list * @throws BallerinaOpenApiException - throws when creating remote functions fails */ - private List createRemoteFunctions(Paths paths, Filter filter) + private List createRemoteFunctions(Paths paths, Filter filter) throws BallerinaOpenApiException { List filterTags = filter.getTags(); @@ -462,7 +477,7 @@ private List createRemoteFunctions(Paths paths, Filter for (Map.Entry operation : path.getValue().readOperationsMap().entrySet()) { // create display annotation of the operation - List functionLevelAnnotationNodes = new ArrayList<>(); + List functionLevelAnnotationNodes = new ArrayList<>(); if (operation.getValue().getExtensions() != null) { Map extensions = operation.getValue().getExtensions(); DocCommentsGenerator.extractDisplayAnnotation(extensions, functionLevelAnnotationNodes); @@ -509,10 +524,10 @@ private List createRemoteFunctions(Paths paths, Filter * } *
*/ - private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(List annotationNodes, - String path, - Map.Entry - operation) + private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(List annotationNodes, + String path, + Map.Entry + operation) throws BallerinaOpenApiException { // Create api doc for function List remoteFunctionDocs = new ArrayList<>(); @@ -530,9 +545,9 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(List qualifierList = createNodeList(createToken( - resourceMode ? - RESOURCE_KEYWORD : - REMOTE_KEYWORD), + resourceMode ? + RESOURCE_KEYWORD : + REMOTE_KEYWORD), createToken(ISOLATED_KEYWORD)); Token functionKeyWord = createToken(FUNCTION_KEYWORD); IdentifierToken functionName = createIdentifierToken( @@ -565,7 +580,7 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(List relativeResourcePath = resourceMode ? - createNodeList(GeneratorUtils.getRelativeResourcePath(path, operation.getValue())) : + createNodeList(GeneratorUtils.getRelativeResourcePath(path, operation.getValue(), null)) : createEmptyNodeList(); return createFunctionDefinitionNode(null, metadataNode, qualifierList, functionKeyWord, functionName, relativeResourcePath, @@ -576,6 +591,7 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(List servers) throws BallerinaOpenApiException { + String serverURL; Server selectedServer = servers.get(0); if (!selectedServer.getUrl().startsWith("https:") && servers.size() > 1) { @@ -602,7 +618,7 @@ private String getServerURL(List servers) throws BallerinaOpenApiExcepti } else { serverURL = selectedServer.getUrl(); } - return serverURL; + return serverURL; } /** @@ -610,14 +626,14 @@ private String getServerURL(List servers) throws BallerinaOpenApiExcepti * * @return {@link Set} */ - public Set getAuthType () { + public Set getAuthType() { return ballerinaAuthConfigGenerator.getAuthType(); } /** * Provide list of the field names in ApiKeysConfig record to generate the Config.toml file. * - * @return {@link List} + * @return {@link List} */ public List getApiKeyNameList() { return apiKeyNameList; @@ -625,7 +641,8 @@ public List getApiKeyNameList() { /** * Set the `apiKeyNameList` by adding the Api Key names available under security schemas. - * @param apiKeyNameList {@link List} + * + * @param apiKeyNameList {@link List} */ public void setApiKeyNameList(List apiKeyNameList) { this.apiKeyNameList = apiKeyNameList; diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaTestGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaTestGenerator.java similarity index 87% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaTestGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaTestGenerator.java index 4722bf072..002a880cd 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaTestGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaTestGenerator.java @@ -1,4 +1,21 @@ -package io.ballerina.openapi.generators.client; +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.AnnotationNode; @@ -33,9 +50,9 @@ import io.ballerina.compiler.syntax.tree.Token; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; import org.apache.commons.io.IOUtils; @@ -82,17 +99,19 @@ 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; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG_PARAM; -import static io.ballerina.openapi.generators.GeneratorConstants.BASIC; -import static io.ballerina.openapi.generators.GeneratorConstants.BEARER; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_CRED; -import static io.ballerina.openapi.generators.GeneratorConstants.PASSWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.REFRESH_TOKEN; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEY; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEY_CONFIG_PARAM; +import static io.ballerina.openapi.core.GeneratorConstants.BASIC; +import static io.ballerina.openapi.core.GeneratorConstants.BEARER; +import static io.ballerina.openapi.core.GeneratorConstants.CLIENT_CRED; +import static io.ballerina.openapi.core.GeneratorConstants.CONNECTION_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.PASSWORD; +import static io.ballerina.openapi.core.GeneratorConstants.REFRESH_TOKEN; /** * This class use for generating boilerplate codes for test cases. + * + * @since 1.3.0 */ public class BallerinaTestGenerator { private final BallerinaClientGenerator ballerinaClientGenerator; @@ -112,10 +131,11 @@ public BallerinaTestGenerator(BallerinaClientGenerator ballerinaClientGenerator) * Generate test.bal file synatx tree. * * @return {@link SyntaxTree} - * @throws IOException Throws exception when syntax tree not modified - * @throws BallerinaOpenApiException Throws exception if open api validation failed + * @throws IOException Throws exception when syntax tree not modified + * @throws BallerinaOpenApiException Throws exception if open api validation failed */ public SyntaxTree generateSyntaxTree() throws IOException, BallerinaOpenApiException { + List functions = new ArrayList<>(); getFunctionDefinitionNodes(functions); List nodes = new ArrayList<>(getModuleVariableDeclarationNodes()); @@ -131,9 +151,10 @@ public SyntaxTree generateSyntaxTree() throws IOException, BallerinaOpenApiExcep /** * Generate import nodes for test.bal file. * - * @return Import node list + * @return Import node list */ - private NodeList getImportNodes () { + private NodeList getImportNodes() { + NodeList imports; ImportDeclarationNode importForTest = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA, GeneratorConstants.MODULE_TEST); @@ -151,15 +172,16 @@ private NodeList getImportNodes () { * Returns String of the relevant config file to the generated test.bal. * * @return {@link String} - * @throws IOException Throws an exception if file not exists + * @throws IOException Throws an exception if file not exists */ - public String getConfigTomlFile () throws IOException { + public String getConfigTomlFile() throws IOException { + ClassLoader classLoader = getClass().getClassLoader(); if (!configFileName.isBlank()) { if (!isHttpOrOAuth) { StringBuilder configFileContent = new StringBuilder("[" + API_KEY_CONFIG_PARAM + "]\n"); - for (String apiKey: ballerinaClientGenerator.getApiKeyNameList()) { + for (String apiKey : ballerinaClientGenerator.getApiKeyNameList()) { configFileContent.append(GeneratorUtils.getValidName(apiKey, false)). append(" = \"\"\n"); } @@ -182,9 +204,9 @@ public String getConfigTomlFile () throws IOException { * Client baseClient = check new Client(clientConfig, serviceUrl = "https://domain/services/data"); * * - * @return {@link List} List of variable declaration nodes + * @return {@link List} List of variable declaration nodes */ - private List getModuleVariableDeclarationNodes () { + private List getModuleVariableDeclarationNodes() { isHttpOrOAuth = true; Set authTypes = ballerinaClientGenerator.getAuthType(); List moduleVariableDeclarationNodes = new ArrayList<>(); @@ -198,7 +220,7 @@ private List getModuleVariableDeclarationNodes () moduleVariableDeclarationNodes.add(getConfigurableVariable(typeBindingPattern)); moduleVariableDeclarationNodes.add(getAuthConfigAssignmentNode()); moduleVariableDeclarationNodes.add(getClientInitializationNode( - GeneratorConstants.CONFIG_RECORD_ARG)); + GeneratorConstants.CONFIG)); configFileName = "basic_config.toml"; break; case BEARER: @@ -207,7 +229,7 @@ private List getModuleVariableDeclarationNodes () moduleVariableDeclarationNodes.add(getConfigurableVariable(typeBindingPattern)); moduleVariableDeclarationNodes.add(getAuthConfigAssignmentNode()); moduleVariableDeclarationNodes.add(getClientInitializationNode( - GeneratorConstants.CONFIG_RECORD_ARG)); + GeneratorConstants.CONFIG)); configFileName = "bearer_config.toml"; break; case CLIENT_CRED: @@ -236,17 +258,13 @@ private List getModuleVariableDeclarationNodes () boolean combinationOfApiKeyAndHTTPOAuth = ballerinaClientGenerator.getBallerinaAuthConfigGenerator() .isApiKey() && ballerinaClientGenerator.getBallerinaAuthConfigGenerator().isHttpOROAuth(); if (combinationOfApiKeyAndHTTPOAuth) { - typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(GeneratorConstants.AUTH_CONFIG_RECORD + " & readonly")); - moduleVariableDeclarationNodes.add(getConfigurableVariable(typeBindingPattern)); - moduleVariableDeclarationNodes.add(getClientInitializationNode - (GeneratorConstants.AUTH_CONFIG)); + // todo : The test file in the combination } else { typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(GeneratorConstants.API_KEYS_CONFIG + " & readonly")); moduleVariableDeclarationNodes.add(getConfigurableVariable(typeBindingPattern)); moduleVariableDeclarationNodes.add(getClientInitializationNode - (GeneratorConstants.API_KEY_CONFIG_PARAM)); + (API_KEY_CONFIG_PARAM)); } configFileName = "api_key_config.toml"; break; @@ -261,19 +279,19 @@ private List getModuleVariableDeclarationNodes () return moduleVariableDeclarationNodes; } - /** * Generate the configurable variable to get auth record from Config.toml. * --ex {@code ClientConfig clientConfig = {authConfig : authConfig};} * - * @return {@link ModuleVariableDeclarationNode} ClientConfig declaration node + * @return {@link ModuleVariableDeclarationNode} ClientConfig declaration node */ - private ModuleVariableDeclarationNode getAuthConfigAssignmentNode () { + private ModuleVariableDeclarationNode getAuthConfigAssignmentNode() { + MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(CLIENT_CONFIG)); + createIdentifierToken(CONNECTION_CONFIG)); CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( - createIdentifierToken(GeneratorConstants.CONFIG_RECORD_ARG)); + createIdentifierToken(GeneratorConstants.CONFIG)); TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, bindingPattern); NodeList nodeList = createEmptyNodeList(); @@ -286,17 +304,18 @@ private ModuleVariableDeclarationNode getAuthConfigAssignmentNode () { /** * Generate the configurable variable to get auth record from Config.toml. * -- ex: Configurable variable for bearer auth mechanism. - * {@code configurable http:BearerTokenConfig & readonly authConfig = ?;} + * {@code configurable http:BearerTokenConfig & readonly authConfig = ?;} * -- ex: Configurable variable for API Key auth mechanism. - * {@code configurable ApiKeysConfig & readonly apiKeyConfig = ?;} + * {@code configurable ApiKeysConfig & readonly apiKeyConfig = ?;} * -- ex: Configurable variable for combination of ApiKey and HTTP/OAuth authentication mechanism. - * {@code configurable AuthConfig & readonly authConfig = ?;} + * {@code configurable AuthConfig & readonly authConfig = ?;} * - * @param typeBindingPattern Variable name - * @return {@link ModuleVariableDeclarationNode} Configurable variable declaration node + * @param typeBindingPattern Variable name + * @return {@link ModuleVariableDeclarationNode} Configurable variable declaration node */ - private ModuleVariableDeclarationNode getConfigurableVariable ( + private ModuleVariableDeclarationNode getConfigurableVariable( BuiltinSimpleNameReferenceNode typeBindingPattern) { + MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); Token configurableNode = createIdentifierToken("configurable"); NodeList nodeList = createNodeList(configurableNode); @@ -308,7 +327,7 @@ private ModuleVariableDeclarationNode getConfigurableVariable ( createIdentifierToken(GeneratorConstants.AUTH_CONFIG)); } else { bindingPattern = createCaptureBindingPatternNode( - createIdentifierToken(GeneratorConstants.API_KEY_CONFIG_PARAM)); + createIdentifierToken(API_KEY_CONFIG_PARAM)); } TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, bindingPattern); @@ -320,14 +339,15 @@ private ModuleVariableDeclarationNode getConfigurableVariable ( /** * Generate client initialization node. * -- ex: Client initialization node of http or OAuth mechanisms. - * {@code Client baseClient = check new Client(clientConfig, serviceUrl = "https://domain/services/data");} + * {@code Client baseClient = check new Client(clientConfig, serviceUrl = "https://domain/services/data");} * -- ex: CClient initialization node for API key auth mechanism. - * {@code Client baseClient = check new Client(apiKeyConfig, serviceUrl = "https://domain/services/data");} + * {@code Client baseClient = check new Client(apiKeyConfig, serviceUrl = "https://domain/services/data");} * - * @param configRecordName Config record name - * @return {@link ModuleVariableDeclarationNode} Client initialization node + * @param configRecordName Config record name + * @return {@link ModuleVariableDeclarationNode} Client initialization node */ - private ModuleVariableDeclarationNode getClientInitializationNode (String configRecordName) { + private ModuleVariableDeclarationNode getClientInitializationNode(String configRecordName) { + String serverURL = ballerinaClientGenerator.getServerUrl(); MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, @@ -343,7 +363,7 @@ private ModuleVariableDeclarationNode getClientInitializationNode (String config PositionalArgumentNode positionalArgumentNode1 = createPositionalArgumentNode(createSimpleNameReferenceNode( createIdentifierToken(configRecordName))); argumentsList.add(positionalArgumentNode1); - Token commaToken = createToken(COMMA_TOKEN); + Token commaToken = createToken(COMMA_TOKEN); argumentsList.add(commaToken); ExpressionNode expressionNode = createRequiredExpressionNode(createIdentifierToken ("\"" + serverURL + "\"")); @@ -370,7 +390,8 @@ private ModuleVariableDeclarationNode getClientInitializationNode (String config * * @return {@link ModuleVariableDeclarationNode} */ - private ModuleVariableDeclarationNode getClientInitForNoAuth () { + private ModuleVariableDeclarationNode getClientInitForNoAuth() { + String serverURL = ballerinaClientGenerator.getServerUrl(); MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, @@ -414,6 +435,7 @@ private ModuleVariableDeclarationNode getClientInitForNoAuth () { * @param functions Empty function definition node list */ private void getFunctionDefinitionNodes(List functions) { + if (!remoteFunctionNameList.isEmpty()) { for (String functionName : remoteFunctionNameList) { MetadataNode metadataNode = getAnnotation(); @@ -456,7 +478,7 @@ private FunctionBodyNode getFunctionBody() { List statementsList = new ArrayList<>(); NodeList statementsNodeList = createNodeList(statementsList); return createFunctionBodyBlockNode(createToken(OPEN_BRACE_TOKEN), - null, statementsNodeList, createToken(CLOSE_BRACE_TOKEN)); + null, statementsNodeList, createToken(CLOSE_BRACE_TOKEN), null); } /** @@ -466,6 +488,7 @@ private FunctionBodyNode getFunctionBody() { * @return {@link MetadataNode} */ private MetadataNode getAnnotation() { + SimpleNameReferenceNode annotateReference = createSimpleNameReferenceNode(createIdentifierToken(GeneratorConstants.ANNOT_TEST)); List fileds = new ArrayList<>(); @@ -480,8 +503,8 @@ private MetadataNode getAnnotation() { /** * Modify function name by capitalizing the first letter. * - * @param name remote function name - * @return formatted name + * @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/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaUtilGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaUtilGenerator.java similarity index 87% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaUtilGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaUtilGenerator.java index e7155bb1d..a629e5282 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/BallerinaUtilGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/BallerinaUtilGenerator.java @@ -1,4 +1,21 @@ -package io.ballerina.openapi.generators.client; +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; import io.ballerina.compiler.syntax.tree.ChildNodeEntry; @@ -22,8 +39,8 @@ import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; -import io.ballerina.openapi.generators.DocCommentsGenerator; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Package; import io.ballerina.projects.Project; @@ -84,20 +101,22 @@ 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.TYPE_KEYWORD; -import static io.ballerina.openapi.generators.GeneratorConstants.BALLERINA; -import static io.ballerina.openapi.generators.GeneratorConstants.DEEP_OBJECT; -import static io.ballerina.openapi.generators.GeneratorConstants.ENCODING; -import static io.ballerina.openapi.generators.GeneratorConstants.ENCODING_STYLE; -import static io.ballerina.openapi.generators.GeneratorConstants.EXPLODE; -import static io.ballerina.openapi.generators.GeneratorConstants.FORM; -import static io.ballerina.openapi.generators.GeneratorConstants.MIME; -import static io.ballerina.openapi.generators.GeneratorConstants.PIPE_DELIMITED; -import static io.ballerina.openapi.generators.GeneratorConstants.SPACE_DELIMITED; -import static io.ballerina.openapi.generators.GeneratorConstants.STYLE; -import static io.ballerina.openapi.generators.GeneratorConstants.URL; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA; +import static io.ballerina.openapi.core.GeneratorConstants.DEEP_OBJECT; +import static io.ballerina.openapi.core.GeneratorConstants.ENCODING; +import static io.ballerina.openapi.core.GeneratorConstants.ENCODING_STYLE; +import static io.ballerina.openapi.core.GeneratorConstants.EXPLODE; +import static io.ballerina.openapi.core.GeneratorConstants.FORM; +import static io.ballerina.openapi.core.GeneratorConstants.MIME; +import static io.ballerina.openapi.core.GeneratorConstants.PIPE_DELIMITED; +import static io.ballerina.openapi.core.GeneratorConstants.SPACE_DELIMITED; +import static io.ballerina.openapi.core.GeneratorConstants.STYLE; +import static io.ballerina.openapi.core.GeneratorConstants.URL; /** * This class is used to generate util file syntax tree according to the generated client. + * + * @since 1.3.0 */ public class BallerinaUtilGenerator { @@ -122,7 +141,7 @@ public class BallerinaUtilGenerator { /** * 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` + * @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; @@ -131,16 +150,17 @@ public void setQueryParamsFound(boolean 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` + * @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` + * @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; @@ -149,7 +169,7 @@ public void setPathParametersFound(boolean flag) { /** * Set `setRequestBodyEncodingFound` flag to `true` when at least one function found with URL-encoded request body. * - * @param flag Function will be called only in the occasions where value needs to be set to `true`. + * @param flag Function will be called only in the occasions where value needs to be set to `true`. */ public void setRequestBodyEncodingFound(boolean flag) { this.requestBodyEncodingFound = flag; @@ -159,7 +179,7 @@ public void setRequestBodyEncodingFound(boolean flag) { * Set `setRequestBodyMultipartFormDatafound` flag to `true` when at least one function found with multipart * form-data request body. * - * @param flag Function will be called only in the occasions where value needs to be set to `true`. + * @param flag Function will be called only in the occasions where value needs to be set to `true`. */ public void setRequestBodyMultipartFormDatafound(boolean flag) { this.requestBodyMultipartFormDatafound = flag; @@ -168,7 +188,7 @@ public void setRequestBodyMultipartFormDatafound(boolean flag) { /** * Generates util file syntax tree. * - * @return Syntax tree of the util.bal file + * @return Syntax tree of the util.bal file */ public SyntaxTree generateUtilSyntaxTree() throws IOException { Set functionNameList = new LinkedHashSet<>(); @@ -176,14 +196,14 @@ public SyntaxTree generateUtilSyntaxTree() throws IOException { functionNameList.addAll(Arrays.asList( CREATE_FORM_URLENCODED_REQUEST_BODY, GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_SERIALIZED_RECORD_ARRAY - )); + )); } if (queryParamsFound) { functionNameList.addAll(Arrays.asList( GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_PATH_FOR_QUERY_PARAM, GET_SERIALIZED_RECORD_ARRAY - )); + )); } if (headersFound) { functionNameList.add(GET_MAP_FOR_HEADERS); @@ -225,7 +245,7 @@ public SyntaxTree generateUtilSyntaxTree() throws IOException { imports.add(importForUrl); } if (requestBodyMultipartFormDatafound) { - ImportDeclarationNode importMime = GeneratorUtils.getImportDeclarationNode(BALLERINA, MIME); + ImportDeclarationNode importMime = GeneratorUtils.getImportDeclarationNode(BALLERINA, MIME); imports.add(importMime); } @@ -240,7 +260,7 @@ public SyntaxTree generateUtilSyntaxTree() throws IOException { /** * Set the type definition nodes related to the util functions generated. * - * @param memberDeclarationNodes {@link ModuleMemberDeclarationNode} + * @param memberDeclarationNodes {@link ModuleMemberDeclarationNode} */ private void getUtilTypeDeclarationNodes(List memberDeclarationNodes) { if (requestBodyEncodingFound || queryParamsFound || headersFound || requestBodyMultipartFormDatafound) { @@ -266,7 +286,7 @@ private void getUtilTypeDeclarationNodes(List membe * }; * * - * @return {@link TypeDefinitionNode} + * @return {@link TypeDefinitionNode} */ private TypeDefinitionNode getEncodingRecord() { // create `style` field @@ -332,7 +352,8 @@ null, createToken(STRING_KEYWORD), createIdentifierToken("contentType"), * PIPEDELIMITED * } * - * @return {@link EnumDeclarationNode} + * + * @return {@link EnumDeclarationNode} */ private EnumDeclarationNode getStyleEnum() { EnumMemberNode deepObject = createEnumMemberNode(null, @@ -348,7 +369,7 @@ private EnumDeclarationNode getStyleEnum() { return createEnumDeclarationNode(null, null, createToken(ENUM_KEYWORD), createIdentifierToken(ENCODING_STYLE), createToken(OPEN_BRACE_TOKEN), - enumMembers, createToken(CLOSE_BRACE_TOKEN)); + enumMembers, createToken(CLOSE_BRACE_TOKEN), null); } /** @@ -356,9 +377,11 @@ private EnumDeclarationNode getStyleEnum() { *
      *     type SimpleBasicType string|boolean|int|float|decimal;
      * 
+ * * @return */ private TypeDefinitionNode getSimpleBasicTypeDefinitionNode() { + TypeDescriptorNode typeDescriptorNode = createSingletonTypeDescriptorNode( createSimpleNameReferenceNode(createIdentifierToken("string|boolean|int|float|decimal"))); return createTypeDefinitionNode(null, null, @@ -371,6 +394,7 @@ private TypeDefinitionNode getSimpleBasicTypeDefinitionNode() { *
      *     final Encoding & readonly defaultEncoding = {};
      * 
+ * * @return */ private ModuleVariableDeclarationNode getDefaultEncoding() { @@ -391,8 +415,8 @@ null, createNodeList(createToken(FINAL_KEYWORD)), bindingPatternNode, /** * Gets the path of the utils_openapi.bal template at the time of execution. * - * @return Path to utils_openapi.bal file in the temporary directory created - * @throws IOException When failed to get the templates/utils_openapi.bal file from resources + * @return Path to utils_openapi.bal file in the temporary directory created + * @throws IOException When failed to get the templates/utils_openapi.bal file from resources */ private Path getResourceFilePath() throws IOException { Path path = null; diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionBodyGenerator.java similarity index 87% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionBodyGenerator.java index 9e6e30b80..359131bdf 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionBodyGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionBodyGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client; +package io.ballerina.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.BlockStatementNode; @@ -41,14 +41,13 @@ import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.mime.MimeType; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.mime.MimeType; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Content; import io.swagger.v3.oas.models.media.MediaType; import io.swagger.v3.oas.models.media.Schema; @@ -100,33 +99,41 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_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.openapi.generators.GeneratorConstants.API_KEYS_CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG_PARAM; -import static io.ballerina.openapi.generators.GeneratorConstants.DELETE; -import static io.ballerina.openapi.generators.GeneratorConstants.ENCODING; -import static io.ballerina.openapi.generators.GeneratorConstants.EXECUTE; -import static io.ballerina.openapi.generators.GeneratorConstants.HEAD; -import static io.ballerina.openapi.generators.GeneratorConstants.HEADER; -import static io.ballerina.openapi.generators.GeneratorConstants.HEADER_VALUES; -import static io.ballerina.openapi.generators.GeneratorConstants.HTTP_HEADERS; -import static io.ballerina.openapi.generators.GeneratorConstants.NILLABLE; -import static io.ballerina.openapi.generators.GeneratorConstants.PATCH; -import static io.ballerina.openapi.generators.GeneratorConstants.POST; -import static io.ballerina.openapi.generators.GeneratorConstants.PUT; -import static io.ballerina.openapi.generators.GeneratorConstants.QUERY; -import static io.ballerina.openapi.generators.GeneratorConstants.QUERY_PARAM; -import static io.ballerina.openapi.generators.GeneratorConstants.RESOURCE_PATH; -import static io.ballerina.openapi.generators.GeneratorConstants.RESPONSE; -import static io.ballerina.openapi.generators.GeneratorConstants.SELF; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.generateBodyStatementForComplexUrl; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.isComplexURL; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEYS_CONFIG; +import static io.ballerina.openapi.core.GeneratorConstants.API_KEY_CONFIG_PARAM; +import static io.ballerina.openapi.core.GeneratorConstants.DELETE; +import static io.ballerina.openapi.core.GeneratorConstants.ENCODING; +import static io.ballerina.openapi.core.GeneratorConstants.EXECUTE; +import static io.ballerina.openapi.core.GeneratorConstants.HEAD; +import static io.ballerina.openapi.core.GeneratorConstants.HEADER; +import static io.ballerina.openapi.core.GeneratorConstants.HEADER_VALUES; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_HEADERS; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.NEW; +import static io.ballerina.openapi.core.GeneratorConstants.NILLABLE; +import static io.ballerina.openapi.core.GeneratorConstants.PATCH; +import static io.ballerina.openapi.core.GeneratorConstants.POST; +import static io.ballerina.openapi.core.GeneratorConstants.PUT; +import static io.ballerina.openapi.core.GeneratorConstants.QUERY; +import static io.ballerina.openapi.core.GeneratorConstants.QUERY_PARAM; +import static io.ballerina.openapi.core.GeneratorConstants.REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.RESOURCE_PATH; +import static io.ballerina.openapi.core.GeneratorConstants.RESPONSE; +import static io.ballerina.openapi.core.GeneratorConstants.SELF; +import static io.ballerina.openapi.core.GeneratorUtils.generateBodyStatementForComplexUrl; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIType; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorUtils.isComplexURL; +import static io.ballerina.openapi.core.GeneratorUtils.isComposedSchema; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.extractReferenceType; /** - * This Util class uses for generating remote function body {@link io.ballerina.compiler.syntax.tree.FunctionBodyNode}. + * This Util class uses for generating remote function body {@link FunctionBodyNode}. + * + * @since 1.3.0 */ public class FunctionBodyGenerator { + private List imports; private boolean isHeader; private final List typeDefinitionNodeList; @@ -164,17 +171,18 @@ public FunctionBodyGenerator(List imports, List operation) throws BallerinaOpenApiException { + NodeList annotationNodes = createEmptyNodeList(); FunctionReturnTypeGenerator functionReturnType = new FunctionReturnTypeGenerator( openAPI, ballerinaSchemaGenerator, typeDefinitionNodeList); isHeader = false; // Create statements - List statementsList = new ArrayList<>(); + List statementsList = new ArrayList<>(); // Check whether given path is complex path , if complex it will handle adding these two statement if (resourceMode && isComplexURL(path)) { List bodyStatements = generateBodyStatementForComplexUrl(path); @@ -201,7 +209,7 @@ public FunctionBodyNode getFunctionBodyNode(String path, Map.Entry statements = createNodeList(statementsList); return createFunctionBodyBlockNode(createToken(OPEN_BRACE_TOKEN), null, statements, - createToken(CLOSE_BRACE_TOKEN)); + createToken(CLOSE_BRACE_TOKEN), null); } /** @@ -232,7 +240,11 @@ private void handleParameterSchemaInOperation(Map.Entry parameters = operation.getValue().getParameters(); - for (Parameter parameter: parameters) { + for (Parameter parameter : parameters) { + if (parameter.get$ref() != null) { + String[] splits = parameter.get$ref().split("/"); + parameter = openAPI.getComponents().getParameters().get(splits[splits.length - 1]); + } if (parameter.getIn().trim().equals(QUERY)) { queryParameters.add(parameter); } else if (parameter.getIn().trim().equals(HEADER)) { @@ -248,8 +260,9 @@ private void handleParameterSchemaInOperation(Map.Entry queryParameters, List headerParameters, - List statementsList, List queryApiKeyNameList, - List headerApiKeyNameList) throws BallerinaOpenApiException { + List statementsList, List queryApiKeyNameList, + List headerApiKeyNameList) throws BallerinaOpenApiException { + boolean combinationOfApiKeyAndHTTPOAuth = ballerinaAuthConfigGenerator.isHttpOROAuth() && ballerinaAuthConfigGenerator.isApiKey(); if (combinationOfApiKeyAndHTTPOAuth) { @@ -280,6 +293,7 @@ public void handleQueryParamsAndHeaders(List queryParameters, List statementsList, List queryApiKeyNameList, List queryParameters, List headerApiKeyNameList, List headerParameters) throws BallerinaOpenApiException { + List ifBodyStatementsList = new ArrayList<>(); if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { @@ -332,11 +346,12 @@ private void addUpdatedPathAndHeaders(List statementsList, List * `queryParam["api-key"] = self.apiKeyConfig?.apiKey;` * `headerValues["api-key"] = self.apiKeyConfig?.apiKey;` */ private void addApiKeysToMap(String mapName, List apiKeyNames, List statementNodeList) { + if (!apiKeyNames.isEmpty()) { for (String apiKey : apiKeyNames) { IdentifierToken fieldName = createIdentifierToken(mapName + "[" + '"' + apiKey.trim() + '"' + "]"); @@ -357,10 +372,10 @@ private void addApiKeysToMap(String mapName, List apiKeyNames, List statementsList, List queryParameters) throws BallerinaOpenApiException { + VariableDeclarationNode queryParamEncodingMap = getQueryParameterEncodingMap(queryParameters); if (queryParamEncodingMap != null) { statementsList.add(queryParamEncodingMap); @@ -386,6 +401,7 @@ private void getUpdatedPathHandlingQueryParamEncoding(List statem */ private void generateIfBlockToAddApiKeysToMaps(List statementsList, List ifBodyStatementsList) { + if (!ifBodyStatementsList.isEmpty()) { NodeList ifBodyStatementsNodeList = createNodeList(ifBodyStatementsList); BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), @@ -407,15 +423,16 @@ private void generateIfBlockToAddApiKeysToMaps(List statementsLis * included to the map even when the serialization mechanisms are specified. These data is given in the `style` and * `explode` sections of the OpenAPI definition. Style defines how multiple values are delimited and explode * specifies whether arrays and objects should generate separate parameters - * + *

* --ex: {@code map queryParamEncoding = {"expand": ["deepObject", true]};} * - * @param queryParameters List of query parameters defined in a particular function - * @return {@link VariableDeclarationNode} - * @throws BallerinaOpenApiException When invalid referenced schema is given. + * @param queryParameters List of query parameters defined in a particular function + * @return {@link VariableDeclarationNode} + * @throws BallerinaOpenApiException When invalid referenced schema is given. */ private VariableDeclarationNode getQueryParameterEncodingMap(List queryParameters) throws BallerinaOpenApiException { + List filedOfMap = new ArrayList<>(); BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("map<" + ENCODING + ">")); @@ -423,15 +440,15 @@ private VariableDeclarationNode getQueryParameterEncodingMap(List que createIdentifierToken("queryParamEncoding")); TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); - for (Parameter parameter: queryParameters) { + for (Parameter parameter : queryParameters) { Schema paramSchema = parameter.getSchema(); if (paramSchema.get$ref() != null) { - paramSchema = openAPI.getComponents().getSchemas().get( + paramSchema = openAPI.getComponents().getSchemas().get( getValidName(extractReferenceType(paramSchema.get$ref()), true)); } if (paramSchema != null && (paramSchema.getProperties() != null || - (paramSchema.getType() != null && paramSchema.getType().equals("array")) || - (paramSchema instanceof ComposedSchema))) { + (getOpenAPIType(paramSchema) != null && getOpenAPIType(paramSchema).equals("array")) || + (isComposedSchema(paramSchema)))) { if (parameter.getStyle() != null || parameter.getExplode() != null) { GeneratorUtils.createEncodingMap(filedOfMap, parameter.getStyle().toString(), parameter.getExplode(), parameter.getName().trim()); @@ -453,10 +470,12 @@ null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, /** * Provides the list of security schemes available for the given operation. - * @param operation Current operation - * @return Security schemes that can be used to authorize the given operation + * + * @param operation Current operation + * @return Security schemes that can be used to authorize the given operation */ private Set getSecurityRequirementForOperation(Operation operation) { + Set securitySchemasAvailable = new LinkedHashSet<>(); List securityRequirements = new ArrayList<>(); if (operation.getSecurity() != null) { @@ -466,7 +485,7 @@ private Set getSecurityRequirementForOperation(Operation operation) { } if (securityRequirements.size() > 0) { - for (SecurityRequirement requirement: securityRequirements) { + for (SecurityRequirement requirement : securityRequirements) { securitySchemasAvailable.addAll(requirement.keySet()); } } @@ -519,9 +538,6 @@ private void createCommonFunctionBodyStatements(List statementsLi ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( "http:Request request = new"); statementsList.add(requestStatementNode); - ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "//TODO: Update the request as needed"); - statementsList.add(expressionStatementNode); clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", request, " + HTTP_HEADERS + ")"; } else if (method.equals(DELETE)) { @@ -540,9 +556,6 @@ private void createCommonFunctionBodyStatements(List statementsLi ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( "http:Request request = new"); statementsList.add(requestStatementNode); - ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "//TODO: Update the request as needed"); - statementsList.add(expressionStatementNode); clientCallStatement = "check self.clientEp-> " + method + "(" + RESOURCE_PATH + ", request)"; } else { clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ")"; @@ -560,13 +573,13 @@ private void createCommonFunctionBodyStatements(List statementsLi /** * This method use to generate Path statement inside the function body node. - * + *

* ex: *

 string  path = string `/weather`; 
* - * @param path - Given path - * @param annotationNodes - Node list for path implementation - * @return - VariableDeclarationNode for path statement. + * @param path - Given path + * @param annotationNodes - Node list for path implementation + * @return - VariableDeclarationNode for path statement. */ private VariableDeclarationNode getPathStatement(String path, NodeList annotationNodes) { @@ -585,7 +598,6 @@ private VariableDeclarationNode getPathStatement(String path, NodeList * http:Request request = new; - * json jsonBody = check payload.cloneWithType(json); + * json jsonBody = payload.toJson(); * request.setPayload(jsonBody, "application/json"); * json response = check self.clientEp->put(path, request); * @@ -627,18 +640,20 @@ public String generatePathWithPathParameter(String path) { * @param returnType - Response type * @param iterator - RequestBody media type */ - private void createRequestBodyStatements(boolean isHeader, List statementsList, - String method, String returnType, Iterator> iterator) + private void createRequestBodyStatements(boolean isHeader, List statementsList, + String method, String returnType, Iterator> iterator) throws BallerinaOpenApiException { //Create Request statement - Map.Entry next = iterator.next(); - VariableDeclarationNode requestVariable = GeneratorUtils.getSimpleStatement("http:Request", - "request", "new"); - statementsList.add(requestVariable); - if (next.getValue() != null) { - genStatementsForRequestMediaType(statementsList, next); + Map.Entry mediaTypeEntry = iterator.next(); + if (GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { + VariableDeclarationNode requestVariable = GeneratorUtils.getSimpleStatement(HTTP_REQUEST, + REQUEST, NEW); + statementsList.add(requestVariable); + } + if (mediaTypeEntry.getValue() != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { + genStatementsForRequestMediaType(statementsList, mediaTypeEntry); // TODO:Fill with other mime type } else { // Add default value comment @@ -676,8 +691,8 @@ private void createRequestBodyStatements(boolean isHeader, List /** * This function is used for generating function body statements according to the given request body media type. * - * @param statementsList - Previous statements list - * @param mediaTypeEntry - Media type entry + * @param statementsList - Previous statements list + * @param mediaTypeEntry - Media type entry */ private void genStatementsForRequestMediaType(List statementsList, Map.Entry mediaTypeEntry) @@ -691,7 +706,7 @@ private void genStatementsForRequestMediaType(List statementsList * This util function for getting type to the targetType data binding. * * @param rType - Given Data type - * @return - return type + * @return - return type */ private String returnTypeForTargetTypeField(String rType) { @@ -705,7 +720,7 @@ private String returnTypeForTargetTypeField(String rType) { * Generate map variable for query parameters and headers. */ private VariableDeclarationNode getMapForParameters(List parameters, String mapDataType, - String mapName, List apiKeyNames) { + String mapName, List apiKeyNames) { List filedOfMap = new ArrayList<>(); BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(mapDataType)); @@ -713,7 +728,7 @@ private VariableDeclarationNode getMapForParameters(List parameters, createIdentifierToken(mapName)); TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); - for (Parameter parameter: parameters) { + for (Parameter parameter : parameters) { // Initializer IdentifierToken fieldName = createIdentifierToken('"' + (parameter.getName().trim()) + '"'); Token colon = createToken(COLON_TOKEN); @@ -758,5 +773,4 @@ private VariableDeclarationNode getMapForParameters(List parameters, null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, createToken(SEMICOLON_TOKEN)); } - } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionReturnTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionReturnTypeGenerator.java similarity index 73% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionReturnTypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionReturnTypeGenerator.java index 168b2c04e..b3283ba8a 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/FunctionReturnTypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/FunctionReturnTypeGenerator.java @@ -1,37 +1,33 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client; +package io.ballerina.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.DocCommentsGenerator; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Content; -import io.swagger.v3.oas.models.media.MapSchema; import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; @@ -50,23 +46,32 @@ import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeDefinitionNode; import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.DEFAULT_RETURN; -import static io.ballerina.openapi.generators.GeneratorConstants.ERROR; -import static io.ballerina.openapi.generators.GeneratorConstants.NILLABLE; -import static io.ballerina.openapi.generators.GeneratorUtils.convertOpenAPITypeToBallerina; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.isValidSchemaName; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_RETURN; +import static io.ballerina.openapi.core.GeneratorConstants.ERROR; +import static io.ballerina.openapi.core.GeneratorConstants.NILLABLE; +import static io.ballerina.openapi.core.GeneratorUtils.convertOpenAPITypeToBallerina; +import static io.ballerina.openapi.core.GeneratorUtils.extractReferenceType; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIType; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorUtils.isValidSchemaName; +import static io.ballerina.openapi.core.GeneratorUtils.isArraySchema; +import static io.ballerina.openapi.core.GeneratorUtils.isComposedSchema; +import static io.ballerina.openapi.core.GeneratorUtils.isMapSchema; +import static io.ballerina.openapi.core.GeneratorUtils.isObjectSchema; /** * This util class for maintain the operation response with ballerina return type. + * + * @since 1.3.0 */ public class FunctionReturnTypeGenerator { private OpenAPI openAPI; private BallerinaTypesGenerator ballerinaSchemaGenerator; private List typeDefinitionNodeList = new LinkedList<>(); - public FunctionReturnTypeGenerator() {} + public FunctionReturnTypeGenerator() { + + } public FunctionReturnTypeGenerator(OpenAPI openAPI, BallerinaTypesGenerator ballerinaSchemaGenerator, List typeDefinitionNodeList) { @@ -79,8 +84,8 @@ public FunctionReturnTypeGenerator(OpenAPI openAPI, BallerinaTypesGenerator ball /** * Get return type of the remote function. * - * @param operation swagger operation. - * @return string with return type. + * @param operation swagger operation. + * @return string with return type. * @throws BallerinaOpenApiException - throws exception if creating return type fails. */ public String getReturnType(Operation operation, boolean isSignature) throws BallerinaOpenApiException { @@ -102,7 +107,7 @@ public String getReturnType(Operation operation, boolean isSignature) throws Bal Schema schema = media.getValue().getSchema(); type = getDataType(operation, isSignature, response, media, type, schema); } else { - type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()); + type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false); } returnTypes.add(type); // Currently support for first media type @@ -135,16 +140,13 @@ private String getDataType(Operation operation, boolean isSignature, ApiResponse Map.Entry media, String type, Schema schema) throws BallerinaOpenApiException { - if (schema instanceof ComposedSchema) { - ComposedSchema composedSchema = (ComposedSchema) schema; - type = generateReturnDataTypeForComposedSchema(operation, type, composedSchema, isSignature); - } else if (schema instanceof ObjectSchema) { - ObjectSchema objectSchema = (ObjectSchema) schema; - type = handleInLineRecordInResponse(operation, media, objectSchema); - } else if (schema instanceof MapSchema) { - MapSchema mapSchema = (MapSchema) schema; - type = handleResponseWithMapSchema(operation, media, mapSchema); - } else if (schema.get$ref() != null) { + if (isComposedSchema(schema)) { + type = generateReturnDataTypeForComposedSchema(operation, type, schema, isSignature); + } else if (isObjectSchema(schema)) { + type = handleInLineRecordInResponse(operation, media, schema); + } else if (isMapSchema(schema)) { + type = handleResponseWithMapSchema(operation, media, schema); + } else if (schema.get$ref() != null) { type = getValidName(extractReferenceType(schema.get$ref()), true); Schema componentSchema = openAPI.getComponents().getSchemas().get(type); if (!isValidSchemaName(type)) { @@ -158,18 +160,17 @@ private String getDataType(Operation operation, boolean isSignature, ApiResponse } TypeDefinitionNode typeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode (componentSchema, type, responseDocs); - updateTypeDefinitionNodeList(type, typeDefinitionNode); + GeneratorUtils.updateTypeDefNodeList(type, typeDefinitionNode, typeDefinitionNodeList); } - } else if (schema instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) schema; + } else if (isArraySchema(schema)) { // TODO: Nested array when response has - type = generateReturnTypeForArraySchema(media, arraySchema, isSignature); - } else if (schema.getType() != null) { - type = convertOpenAPITypeToBallerina(schema.getType()); + type = generateReturnTypeForArraySchema(media, schema, isSignature); + } else if (getOpenAPIType(schema) != null) { + type = convertOpenAPITypeToBallerina(schema); } else if (media.getKey().trim().equals("application/xml")) { type = generateCustomTypeDefine("xml", "XML", isSignature); } else { - type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()); + type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false); } return type; } @@ -177,8 +178,9 @@ private String getDataType(Operation operation, boolean isSignature, ApiResponse /** * Get the return data type according to the OAS ArraySchema. */ - private String generateReturnTypeForArraySchema(Map.Entry media, ArraySchema arraySchema, + private String generateReturnTypeForArraySchema(Map.Entry media, Schema arraySchema, boolean isSignature) throws BallerinaOpenApiException { + String type; if (arraySchema.getItems().get$ref() != null) { String name = getValidName(extractReferenceType(arraySchema.getItems().get$ref()), true); @@ -190,36 +192,35 @@ private String generateReturnTypeForArraySchema(Map.Entry med createSimpleNameReferenceNode(createIdentifierToken(type)), createToken(SEMICOLON_TOKEN)); // Check already typeDescriptor has same name - updateTypeDefinitionNodeList(typeName, typeDefNode); + GeneratorUtils.updateTypeDefNodeList(typeName, typeDefNode, typeDefinitionNodeList); if (!isSignature) { type = typeName; } - } else if (arraySchema.getItems().getType() == null) { + } else if (getOpenAPIType(arraySchema.getItems()) == null) { if (media.getKey().trim().equals("application/xml")) { type = generateCustomTypeDefine("xml[]", "XMLArr", isSignature); } else if (media.getKey().trim().equals("application/pdf") || media.getKey().trim().equals("image/png") || media.getKey().trim().equals("application/octet-stream")) { - String typeName = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()) + "Arr"; - type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()); - type = generateCustomTypeDefine(type, typeName, isSignature); + String typeName = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false) + "Arr"; + String mappedType = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false); + type = generateCustomTypeDefine(mappedType, typeName, isSignature); } else { - String typeName = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()) + "Arr"; - type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim()) + "[]"; - type = generateCustomTypeDefine(type, typeName, isSignature); + String typeName = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false) + "Arr"; + String mappedType = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false) + "[]"; + type = generateCustomTypeDefine(mappedType, typeName, isSignature); } } else { String typeName; - if (arraySchema.getItems() instanceof ArraySchema) { + if (isArraySchema(arraySchema.getItems())) { Schema nestedSchema = arraySchema.getItems(); - ArraySchema nestedArraySchema = (ArraySchema) nestedSchema; - String inlineArrayType = convertOpenAPITypeToBallerina(nestedArraySchema.getItems().getType()); - typeName = inlineArrayType + "NestedArr"; + String inlineArrayType = convertOpenAPITypeToBallerina(nestedSchema.getItems()); + typeName = inlineArrayType + "NestedArr"; type = inlineArrayType + "[][]"; } else { - typeName = convertOpenAPITypeToBallerina(Objects.requireNonNull(arraySchema.getItems()).getType()) + + typeName = convertOpenAPITypeToBallerina(Objects.requireNonNull(arraySchema.getItems())) + "Arr"; - type = convertOpenAPITypeToBallerina(arraySchema.getItems().getType()) + "[]"; + type = convertOpenAPITypeToBallerina(arraySchema.getItems()) + "[]"; } type = generateCustomTypeDefine(type, getValidName(typeName, true), isSignature); } @@ -230,14 +231,15 @@ private String generateReturnTypeForArraySchema(Map.Entry med * Get the return data type according to the OAS ComposedSchemas ex: AllOf, OneOf, AnyOf. */ private String generateReturnDataTypeForComposedSchema(Operation operation, String type, - ComposedSchema composedSchema, boolean isSignature) + Schema composedSchema, boolean isSignature) throws BallerinaOpenApiException { + if (composedSchema.getOneOf() != null) { // Get oneOfUnionType name - String typeName = "OneOf" + getValidName(operation.getOperationId().trim(), true) + "Response"; + String typeName = "OneOf" + getValidName(operation.getOperationId().trim(), true) + "Response"; TypeDefinitionNode typeDefNode = ballerinaSchemaGenerator.getTypeDefinitionNode( composedSchema, typeName, new ArrayList<>()); - updateTypeDefinitionNodeList(typeName, typeDefNode); + GeneratorUtils.updateTypeDefNodeList(typeName, typeDefNode, typeDefinitionNodeList); type = typeDefNode.typeDescriptor().toString(); if (!isSignature) { type = typeName; @@ -247,7 +249,7 @@ private String generateReturnDataTypeForComposedSchema(Operation operation, Stri "Response"; TypeDefinitionNode allOfTypeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode (composedSchema, recordName, new ArrayList<>()); - updateTypeDefinitionNodeList(recordName, allOfTypeDefinitionNode); + GeneratorUtils.updateTypeDefNodeList(recordName, allOfTypeDefinitionNode, typeDefinitionNodeList); type = recordName; } return type; @@ -257,8 +259,9 @@ private String generateReturnDataTypeForComposedSchema(Operation operation, Stri * Handle inline record by generating record with name for response in OAS type ObjectSchema. */ private String handleInLineRecordInResponse(Operation operation, Map.Entry media, - ObjectSchema objectSchema) + Schema objectSchema) throws BallerinaOpenApiException { + Map properties = objectSchema.getProperties(); String ref = objectSchema.get$ref(); String type = getValidName(operation.getOperationId(), true) + "Response"; @@ -267,7 +270,7 @@ private String handleInLineRecordInResponse(Operation operation, Map.Entry returnTypeDocs = new ArrayList<>(); String description = operation.getResponses().entrySet().iterator().next().getValue().getDescription(); @@ -277,10 +280,10 @@ private String handleInLineRecordInResponse(Operation operation, Map.Entry media, - MapSchema mapSchema) throws BallerinaOpenApiException { + Schema mapSchema) throws BallerinaOpenApiException { + Map properties = mapSchema.getProperties(); String ref = mapSchema.get$ref(); String type = getValidName(operation.getOperationId(), true) + "Response"; @@ -298,7 +302,7 @@ private String handleResponseWithMapSchema(Operation operation, Map.Entry schemaDocs = new ArrayList<>(); String description = operation.getResponses().entrySet().iterator().next().getValue().getDescription(); @@ -308,10 +312,10 @@ private String handleResponseWithMapSchema(Operation operation, Map.Entry typeDefinitionNodeList; private FunctionReturnTypeGenerator functionReturnType; private boolean deprecatedParamFound = false; - private boolean isResource; + public List getTypeDefinitionNodeList() { return typeDefinitionNodeList; } @@ -127,7 +129,7 @@ public FunctionSignatureGenerator(OpenAPI openAPI, this.openAPI = openAPI; this.ballerinaSchemaGenerator = ballerinaSchemaGenerator; this.typeDefinitionNodeList = typeDefinitionNodeList; - this.functionReturnType = new FunctionReturnTypeGenerator + this.functionReturnType = new FunctionReturnTypeGenerator (openAPI, ballerinaSchemaGenerator, typeDefinitionNodeList); this.isResource = isResource; @@ -136,17 +138,18 @@ public FunctionSignatureGenerator(OpenAPI openAPI, /** * This function for generate function signatures. * - * @param operation - openapi operation - * @return {@link io.ballerina.compiler.syntax.tree.FunctionSignatureNode} + * @param operation - openapi operation + * @return {@link FunctionSignatureNode} * @throws BallerinaOpenApiException - throws exception when node creation fails. */ public FunctionSignatureNode getFunctionSignatureNode(Operation operation, List remoteFunctionDoc) throws BallerinaOpenApiException { // Store the parameters for method. - List parameterList = new ArrayList<>(); - functionReturnType = new FunctionReturnTypeGenerator - (openAPI, ballerinaSchemaGenerator, typeDefinitionNodeList); + List parameterList = new ArrayList<>(); + setFunctionParameters(operation, parameterList, createToken(COMMA_TOKEN), remoteFunctionDoc); + functionReturnType = new FunctionReturnTypeGenerator + (openAPI, ballerinaSchemaGenerator, typeDefinitionNodeList); if (parameterList.size() >= 2) { parameterList.remove(parameterList.size() - 1); @@ -157,11 +160,14 @@ public FunctionSignatureNode getFunctionSignatureNode(Operation operation, List< ApiResponses responses = operation.getResponses(); Collection values = responses.values(); Iterator iteratorRes = values.iterator(); - ApiResponse next = iteratorRes.next(); - if (next.getDescription() != null && !next.getDescription().isBlank()) { - MarkdownParameterDocumentationLineNode returnDoc = DocCommentsGenerator.createAPIParamDoc("return", - next.getDescription()); - remoteFunctionDoc.add(returnDoc); + if (iteratorRes.hasNext()) { + ApiResponse response = iteratorRes.next(); + if (response.getDescription() != null && !response.getDescription().isBlank()) { + MarkdownParameterDocumentationLineNode returnDoc = + DocCommentsGenerator.createAPIParamDoc("return", + response.getDescription()); + remoteFunctionDoc.add(returnDoc); + } } // Return Type @@ -176,21 +182,30 @@ public FunctionSignatureNode getFunctionSignatureNode(Operation operation, List< * Generate function parameters. */ private void setFunctionParameters(Operation operation, List parameterList, Token comma, - List remoteFunctionDoc) throws BallerinaOpenApiException { + List remoteFunctionDoc) throws BallerinaOpenApiException { + List parameters = operation.getParameters(); List defaultable = new ArrayList<>(); List deprecatedParamDocComments = new ArrayList<>(); if (parameters != null) { - for (Parameter parameter: parameters) { + for (Parameter parameter : parameters) { if (parameter.getDescription() != null && !parameter.getDescription().isBlank()) { - MarkdownParameterDocumentationLineNode paramAPIDoc = - DocCommentsGenerator.createAPIParamDoc(getValidName( - parameter.getName(), false), parameter.getDescription()); + MarkdownDocumentationNode paramAPIDoc = + DocCommentsGenerator.createAPIParamDocFromSring(getValidName( + parameter.getName(), false), parameter.getDescription()); remoteFunctionDoc.add(paramAPIDoc); } List parameterAnnotationNodeList = getParameterAnnotationNodeList(parameter, deprecatedParamDocComments); - String in = parameter.getIn(); + String in; + if (parameter.get$ref() != null) { + String paramType = extractReferenceType(parameter.get$ref()); + parameter = openAPI.getComponents().getParameters().get(paramType); + in = parameter.getIn(); + } else { + in = parameter.getIn(); + } + switch (in) { case "path": Node param = getPathParameters(parameter, createNodeList(parameterAnnotationNodeList)); @@ -228,16 +243,8 @@ private void setFunctionParameters(Operation operation, List parameterList // Handle RequestBody if (operation.getRequestBody() != null) { - RequestBody requestBody = operation.getRequestBody(); - if (requestBody.getContent() != null) { - setRequestBodyParameters(operation.getOperationId(), requestBody, remoteFunctionDoc, parameterList, - defaultable); - } else if (requestBody.get$ref() != null) { - String requestBodyName = extractReferenceType(requestBody.get$ref()); - RequestBody requestBodySchema = openAPI.getComponents().getRequestBodies().get(requestBodyName.trim()); - setRequestBodyParameters(operation.getOperationId(), requestBodySchema, remoteFunctionDoc, - parameterList, defaultable); - } + setRequestBodyParameters(operation.getOperationId(), operation.getRequestBody(), remoteFunctionDoc, + parameterList, defaultable); } remoteFunctionDoc.addAll(deprecatedParamDocComments); //Filter defaultable parameters @@ -247,7 +254,7 @@ private void setFunctionParameters(Operation operation, List parameterList } private List getParameterAnnotationNodeList(Parameter parameter, - List deprecatedParamDocComments) { + List deprecatedParamDocComments) { List parameterAnnotationNodeList = new ArrayList<>(); DocCommentsGenerator.extractDisplayAnnotation(parameter.getExtensions(), parameterAnnotationNodeList); if (parameter.getDeprecated() != null && parameter.getDeprecated()) { @@ -258,7 +265,7 @@ private List getParameterAnnotationNodeList(Parameter parameter, } String deprecatedDescription = ""; if (parameter.getExtensions() != null) { - for (Map.Entry extension: parameter.getExtensions().entrySet()) { + for (Map.Entry extension : parameter.getExtensions().entrySet()) { if (extension.getKey().trim().equals(X_BALLERINA_DEPRECATED_REASON)) { deprecatedDescription = extension.getValue().toString(); break; @@ -277,41 +284,43 @@ private List getParameterAnnotationNodeList(Parameter parameter, /** * Create query parameters. - * + *

* Note: currently ballerina supports for this data type. * type BasicType boolean|int|float|decimal|string; * public type QueryParamType ()|BasicType|BasicType[]; */ public Node getQueryParameters(Parameter parameter, NodeList parameterAnnotationNodeList) throws BallerinaOpenApiException { + TypeDescriptorNode typeName; Schema parameterSchema = parameter.getSchema(); String paramType = ""; if (parameterSchema.get$ref() != null) { paramType = getValidName(extractReferenceType(parameterSchema.get$ref()), true); + parameterSchema = openAPI.getComponents().getSchemas().get(paramType.trim()); } else { - paramType = convertOpenAPITypeToBallerina(parameterSchema.getType().trim()); - if (parameterSchema.getType().equals(NUMBER)) { - if (parameterSchema.getFormat() != null) { - paramType = convertOpenAPITypeToBallerina(parameterSchema.getFormat().trim()); - } - } else if (parameterSchema instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) parameterSchema; - if (arraySchema.getItems().getType() != null) { - String itemType = arraySchema.getItems().getType(); - if (itemType.equals(STRING) || itemType.equals(INTEGER) || itemType.equals(BOOLEAN)) { - paramType = convertOpenAPITypeToBallerina(itemType) + SQUARE_BRACKETS; - } else if (itemType.equals(NUMBER)) { - paramType = convertOpenAPITypeToBallerina - (arraySchema.getItems().getFormat().trim()) + SQUARE_BRACKETS; + paramType = convertOpenAPITypeToBallerina(parameterSchema); + if (getOpenAPIType(parameterSchema).equals(ARRAY)) { + if (getOpenAPIType(parameterSchema.getItems()) != null) { + String itemType = getOpenAPIType(parameterSchema.getItems()); + if (itemType.equals(STRING) || itemType.equals(INTEGER) || itemType.equals(BOOLEAN) || + itemType.equals(NUMBER)) { + if (parameterSchema.getItems().getEnum() != null && + !parameterSchema.getItems().getEnum().isEmpty()) { + paramType = OPEN_PAREN_TOKEN.stringValue() + + convertOpenAPITypeToBallerina(parameterSchema.getItems()) + + CLOSE_PAREN_TOKEN.stringValue() + SQUARE_BRACKETS; + } else { + paramType = convertOpenAPITypeToBallerina(parameterSchema.getItems()) + SQUARE_BRACKETS; + } } else { throw new BallerinaOpenApiException("Unsupported parameter type is found in the parameter : " + parameter.getName()); } - } else if (arraySchema.getItems().get$ref() != null) { + } else if (parameterSchema.getItems().get$ref() != null) { paramType = getValidName(extractReferenceType( - arraySchema.getItems().get$ref().trim()), true) + SQUARE_BRACKETS; + parameterSchema.getItems().get$ref().trim()), true) + SQUARE_BRACKETS; } else { throw new BallerinaOpenApiException("Please define the array item type of the parameter : " + parameter.getName()); @@ -330,10 +339,10 @@ public Node getQueryParameters(Parameter parameter, NodeList par if (parameterSchema.getDefault() != null) { typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(paramType)); LiteralValueToken literalValueToken; - if (parameterSchema.getType().equals(STRING)) { + if (getOpenAPIType(parameterSchema).equals(STRING)) { literalValueToken = createLiteralValueToken(null, '"' + parameterSchema.getDefault().toString() + '"', createEmptyMinutiaeList(), - createEmptyMinutiaeList()); + createEmptyMinutiaeList()); } else { literalValueToken = createLiteralValueToken(null, parameterSchema.getDefault().toString(), @@ -344,8 +353,9 @@ public Node getQueryParameters(Parameter parameter, NodeList par return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, createToken(EQUAL_TOKEN), literalValueToken); } else { - typeName = createOptionalTypeDescriptorNode(createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(paramType)), createToken(QUESTION_MARK_TOKEN)); + paramType = paramType.endsWith(NILLABLE) ? paramType : paramType + NILLABLE; + typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(paramType)); NilLiteralNode nilLiteralNode = createNilLiteralNode(createToken(OPEN_PAREN_TOKEN), createToken(CLOSE_PAREN_TOKEN)); return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, @@ -366,11 +376,11 @@ public Node getPathParameters(Parameter parameter, NodeList para if (parameterSchema.get$ref() != null) { type = getValidName(extractReferenceType(parameterSchema.get$ref()), true); Schema schema = openAPI.getComponents().getSchemas().get(type.trim()); - if (schema instanceof ObjectSchema) { + if (isObjectSchema(schema) || (isComposedSchema(schema) && schema.getAllOf() != null)) { throw new BallerinaOpenApiException("Ballerina does not support object type path parameters."); } } else { - type = convertOpenAPITypeToBallerina(parameter.getSchema().getType().trim()); + type = convertOpenAPITypeToBallerina(parameter.getSchema()); if (type.equals("anydata") || type.equals(SQUARE_BRACKETS) || type.equals("record {}")) { throw new BallerinaOpenApiException(invalidPathParamType(parameter.getName().trim())); } @@ -385,6 +395,7 @@ public Node getPathParameters(Parameter parameter, NodeList para */ private Node getHeaderParameter(Parameter parameter, NodeList parameterAnnotationNodeList) throws BallerinaOpenApiException { + Schema schema = parameter.getSchema(); IdentifierToken paramName = createIdentifierToken(getValidName(parameter.getName().trim(), false)); return getHeader(parameter.getRequired(), schema, paramName, parameterAnnotationNodeList); @@ -395,6 +406,7 @@ private Node getHeaderParameter(Parameter parameter, NodeList pa */ private Node getHeaderEncoding(Map.Entry parameter, List remoteFunctionDoc) throws BallerinaOpenApiException { + boolean isRequired = false; Schema schema = parameter.getValue().getSchema(); IdentifierToken paramName = createIdentifierToken(getValidName(parameter.getKey(), false)); @@ -419,14 +431,17 @@ private Node getHeaderEncoding(Map.Entry parameter, List r */ private Node getHeader(boolean isRequiredHeader, Schema schema, IdentifierToken paramName, NodeList parameterAnnotationNodeList) throws BallerinaOpenApiException { + if (isRequiredHeader) { - String type = convertOpenAPITypeToBallerina(schema.getType().trim()); - if (schema instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) schema; - if (arraySchema.getItems().get$ref() != null) { - type = extractReferenceType(arraySchema.getItems().get$ref()) + SQUARE_BRACKETS; + String type = convertOpenAPITypeToBallerina(schema); + if (isArraySchema(schema)) { + if (schema.getItems().get$ref() != null) { + type = extractReferenceType(schema.getItems().get$ref()) + SQUARE_BRACKETS; + } else if (schema.getItems().getEnum() != null && !schema.getItems().getEnum().isEmpty()) { + type = OPEN_PAREN_TOKEN.stringValue() + convertOpenAPITypeToBallerina(schema.getItems()) + + CLOSE_PAREN_TOKEN.stringValue() + SQUARE_BRACKETS; } else { - type = convertOpenAPITypeToBallerina(arraySchema.getItems().getType().trim()) + SQUARE_BRACKETS; + type = convertOpenAPITypeToBallerina(schema.getItems()) + SQUARE_BRACKETS; } } BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, @@ -435,9 +450,9 @@ private Node getHeader(boolean isRequiredHeader, Schema schema, IdentifierToken } else { if (schema.getDefault() != null) { BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(convertOpenAPITypeToBallerina(schema.getType().trim()))); + createIdentifierToken(convertOpenAPITypeToBallerina(schema))); LiteralValueToken literalValueToken; - if (schema.getType().equals(STRING)) { + if (getOpenAPIType(schema).equals(STRING)) { literalValueToken = createLiteralValueToken(null, '"' + schema.getDefault().toString() + '"', createEmptyMinutiaeList(), createEmptyMinutiaeList()); @@ -448,18 +463,25 @@ private Node getHeader(boolean isRequiredHeader, Schema schema, IdentifierToken return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, createToken(EQUAL_TOKEN), literalValueToken); } else { - String type = convertOpenAPITypeToBallerina(schema.getType().trim()) + NILLABLE; - if (schema instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) schema; - if (arraySchema.getItems().get$ref() != null) { - type = extractReferenceType(arraySchema.getItems().get$ref()) + SQUARE_BRACKETS + NILLABLE; + String type = convertOpenAPITypeToBallerina(schema); + String nillableType = type.endsWith(NILLABLE) ? type : type + NILLABLE; + if (isArraySchema(schema)) { + if (schema.getItems().get$ref() != null) { + nillableType = extractReferenceType(schema.getItems().get$ref()) + + SQUARE_BRACKETS + NILLABLE; + } else if (schema.getItems().getEnum() != null && + !schema.getItems().getEnum().isEmpty()) { + nillableType = OPEN_PAREN_TOKEN.stringValue() + + convertOpenAPITypeToBallerina(schema.getItems()) + + CLOSE_PAREN_TOKEN.stringValue() + SQUARE_BRACKETS + + NILLABLE; } else { - type = convertOpenAPITypeToBallerina(arraySchema.getItems().getType().trim()) + SQUARE_BRACKETS + nillableType = convertOpenAPITypeToBallerina(schema.getItems()) + SQUARE_BRACKETS + NILLABLE; } } BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(type)); + createIdentifierToken(nillableType)); NilLiteralNode nilLiteralNode = createNilLiteralNode(createToken(OPEN_PAREN_TOKEN), createToken(CLOSE_PAREN_TOKEN)); return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, @@ -474,48 +496,64 @@ private Node getHeader(boolean isRequiredHeader, Schema schema, IdentifierToken private void setRequestBodyParameters(String operationId, RequestBody requestBody, List requestBodyDoc, List parameterList, List defaultable) throws BallerinaOpenApiException { - Content content = requestBody.getContent(); - Iterator> iterator = content.entrySet().iterator(); + + Content requestBodyContent; + String referencedRequestBodyName = ""; + if (requestBody.get$ref() != null) { + referencedRequestBodyName = extractReferenceType(requestBody.get$ref()).trim(); + RequestBody referencedRequestBody = openAPI.getComponents() + .getRequestBodies().get(referencedRequestBodyName); + requestBodyContent = referencedRequestBody.getContent(); + // note : when there is referenced request body, the description at the reference is ignored. + // Need to consider the description at the component level + requestBody.setDescription(referencedRequestBody.getDescription()); + } else { + requestBodyContent = requestBody.getContent(); + } + + Iterator> iterator = requestBodyContent.entrySet().iterator(); while (iterator.hasNext()) { // This implementation currently for first content type - Map.Entry next = iterator.next(); - Schema schema = next.getValue().getSchema(); + Map.Entry mediaTypeEntry = iterator.next(); + Schema schema = mediaTypeEntry.getValue().getSchema(); String paramType = ""; //Take payload type - if (schema != null) { - if (next.getKey().equals(ANY_TYPE) || next.getKey().contains(VENDOR_SPECIFIC_TYPE)) { - paramType = SyntaxKind.BYTE_KEYWORD.stringValue() + SQUARE_BRACKETS; - } else if (schema.get$ref() != null) { - paramType = getValidName(extractReferenceType(schema.get$ref().trim()), true); - } else if (schema.getType() != null && !schema.getType().equals(ARRAY) && !schema.getType().equals( - OBJECT)) { - String typeOfPayload = schema.getType().trim(); - if (typeOfPayload.equals(STRING) && schema.getFormat() != null - && (schema.getFormat().equals(BINARY) || schema.getFormat().equals(BYTE))) { - paramType = convertOpenAPITypeToBallerina(schema.getFormat()); - } else { - paramType = convertOpenAPITypeToBallerina(typeOfPayload); + if (schema != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { + String mediaTypeEntryKey = mediaTypeEntry.getKey(); + if (mediaTypeEntryKey.equals(APPLICATION_OCTET_STREAM) || + mediaTypeEntryKey.matches("application/.*\\+octet-stream")) { + paramType = getBallerinaMediaType(mediaTypeEntryKey, true); + } else { + if (schema.get$ref() != null) { + paramType = getValidName(extractReferenceType(schema.get$ref().trim()), true); + } else if (getOpenAPIType(schema) != null && !getOpenAPIType(schema).equals(ARRAY) && + !getOpenAPIType(schema).equals( + OBJECT)) { + paramType = convertOpenAPITypeToBallerina(schema); + } else if (isArraySchema(schema)) { + //TODO: handle nested array - this is impossible to handle + paramType = getRequestBodyParameterForArraySchema(operationId, mediaTypeEntry, schema); + } else if (isObjectSchema(schema) || schema.getProperties() != null) { + paramType = getRequestBodyParameterForObjectSchema(referencedRequestBodyName, schema); + } else { // composed and object schemas are handled by the flatten + paramType = getBallerinaMediaType(mediaTypeEntryKey, true); } - } else if (schema instanceof ArraySchema) { - //TODO: handle nested array - this is impossible to handle - ArraySchema arraySchema = (ArraySchema) schema; - paramType = getRequestBodyParameterForArraySchema(operationId, next, arraySchema); - } else { // composed and object schemas are handled by the flatten - paramType = GeneratorUtils.getBallerinaMediaType(next.getKey()); } } else { - paramType = GeneratorUtils.getBallerinaMediaType(next.getKey()); + paramType = getBallerinaMediaType(mediaTypeEntry.getKey(), true); } + + String paramName = paramType.equals(HTTP_REQUEST) ? REQUEST : PAYLOAD; if (!paramType.isBlank()) { - List annotationNodes = new ArrayList<>(); + List annotationNodes = new ArrayList<>(); DocCommentsGenerator.extractDisplayAnnotation(requestBody.getExtensions(), annotationNodes); SimpleNameReferenceNode typeName = createSimpleNameReferenceNode(createIdentifierToken(paramType)); - IdentifierToken paramName = createIdentifierToken(PAYLOAD); + IdentifierToken paramNameToken = createIdentifierToken(paramName); RequiredParameterNode payload = createRequiredParameterNode( - createNodeList(annotationNodes), typeName, paramName); + createNodeList(annotationNodes), typeName, paramNameToken); if (requestBody.getDescription() != null && !requestBody.getDescription().isBlank()) { - MarkdownParameterDocumentationLineNode paramAPIDoc = - DocCommentsGenerator.createAPIParamDoc(escapeIdentifier(PAYLOAD), + MarkdownDocumentationNode paramAPIDoc = + DocCommentsGenerator.createAPIParamDocFromSring(escapeIdentifier(paramName), requestBody.getDescription().split("\n")[0]); requestBodyDoc.add(paramAPIDoc); } @@ -523,10 +561,10 @@ private void setRequestBodyParameters(String operationId, RequestBody requestBod parameterList.add(createToken((COMMA_TOKEN))); } - if (next.getKey().equals(javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA) - && next.getValue().getEncoding() != null) { + if (mediaTypeEntry.getKey().equals(javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA) + && mediaTypeEntry.getValue().getEncoding() != null) { List headerList = new ArrayList<>(); - for (Map.Entry entry : next.getValue().getEncoding().entrySet()) { + for (Map.Entry entry : mediaTypeEntry.getValue().getEncoding().entrySet()) { if (entry.getValue().getHeaders() != null) { for (Map.Entry header : entry.getValue().getHeaders().entrySet()) { if (!headerList.contains(header.getKey())) { @@ -548,27 +586,40 @@ private void setRequestBodyParameters(String operationId, RequestBody requestBod } } + private String getRequestBodyParameterForObjectSchema (String recordName, Schema objectSchema) + throws BallerinaOpenApiException { + recordName = getValidName(recordName + "_RequestBody", true); + if (objectSchema.getProperties() == null || objectSchema.getProperties().isEmpty()) { + return EMPTY_RECORD; + } + TypeDefinitionNode record = + ballerinaSchemaGenerator.getTypeDefinitionNode(objectSchema, recordName, new ArrayList<>()); + GeneratorUtils.updateTypeDefNodeList(recordName, record, typeDefinitionNodeList); + return recordName; + } + /** * Generate RequestBody for array type schema. */ private String getRequestBodyParameterForArraySchema(String operationId, Map.Entry next, - ArraySchema arraySchema) throws BallerinaOpenApiException { + Schema arraySchema) throws BallerinaOpenApiException { String paramType; Schema arrayItems = arraySchema.getItems(); - if (arrayItems.getType() != null) { - paramType = convertOpenAPITypeToBallerina(arrayItems.getType()) + SQUARE_BRACKETS; + if (getOpenAPIType(arrayItems) != null) { + paramType = convertOpenAPITypeToBallerina(arrayItems) + SQUARE_BRACKETS; } else if (arrayItems.get$ref() != null) { paramType = getValidName(extractReferenceType(arrayItems.get$ref()), true) + SQUARE_BRACKETS; - } else if (arrayItems instanceof ComposedSchema) { - paramType = "CompoundArrayItem" + getValidName(operationId, true) + "Request"; + } else if (isComposedSchema(arrayItems)) { + paramType = "CompoundArrayItem" + getValidName(operationId, true) + "Request"; // TODO - Add API doc by checking requestBody TypeDefinitionNode arrayTypeNode = ballerinaSchemaGenerator.getTypeDefinitionNode(arraySchema, paramType, new ArrayList<>()); - functionReturnType.updateTypeDefinitionNodeList(paramType, arrayTypeNode); + GeneratorUtils.updateTypeDefNodeList(paramType, arrayTypeNode, typeDefinitionNodeList); } else { - paramType = GeneratorUtils.getBallerinaMediaType(next.getKey().trim()) + SQUARE_BRACKETS; + paramType = getBallerinaMediaType(next.getKey().trim(), true) + SQUARE_BRACKETS; } return paramType; } + } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/MimeFactory.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/MimeFactory.java similarity index 54% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/MimeFactory.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/MimeFactory.java index 8cd10ffa6..c627da90a 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/MimeFactory.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/MimeFactory.java @@ -1,92 +1,88 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client; +package io.ballerina.openapi.core.generators.client; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.client.mime.AnyType; -import io.ballerina.openapi.generators.client.mime.CustomType; -import io.ballerina.openapi.generators.client.mime.JsonType; -import io.ballerina.openapi.generators.client.mime.MimeType; -import io.ballerina.openapi.generators.client.mime.MultipartFormData; -import io.ballerina.openapi.generators.client.mime.OctedStreamType; -import io.ballerina.openapi.generators.client.mime.UrlEncodedType; -import io.ballerina.openapi.generators.client.mime.XmlType; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.client.mime.CustomType; +import io.ballerina.openapi.core.generators.client.mime.JsonType; +import io.ballerina.openapi.core.generators.client.mime.MimeType; +import io.ballerina.openapi.core.generators.client.mime.MultipartFormData; +import io.ballerina.openapi.core.generators.client.mime.OctetStreamType; +import io.ballerina.openapi.core.generators.client.mime.UrlEncodedType; +import io.ballerina.openapi.core.generators.client.mime.XmlType; import io.swagger.v3.oas.models.media.MediaType; import io.swagger.v3.oas.models.media.Schema; import java.util.List; import java.util.Map; - -import static io.ballerina.openapi.generators.GeneratorConstants.ANY_TYPE; -import static io.ballerina.openapi.generators.GeneratorConstants.IMAGE; -import static io.ballerina.openapi.generators.GeneratorConstants.JSON; -import static io.ballerina.openapi.generators.GeneratorConstants.PDF; -import static io.ballerina.openapi.generators.GeneratorConstants.TEXT_PREFIX; -import static io.ballerina.openapi.generators.GeneratorConstants.UNSUPPORTED_MEDIA_ERROR; -import static io.ballerina.openapi.generators.GeneratorConstants.VENDOR_SPECIFIC_TYPE; -import static io.ballerina.openapi.generators.GeneratorConstants.XML; +import static io.ballerina.openapi.core.GeneratorConstants.IMAGE; +import static io.ballerina.openapi.core.GeneratorConstants.PDF; +import static io.ballerina.openapi.core.GeneratorConstants.TEXT_PREFIX; +import static io.ballerina.openapi.core.GeneratorConstants.UNSUPPORTED_MEDIA_ERROR; +import static io.ballerina.openapi.core.GeneratorConstants.VENDOR_SPECIFIC_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA; - /** - * Factory class for mime type creation. + * Factory class for mime type creation. * - * @since 2.0.0 + * @since 1.3.0 */ public class MimeFactory { /** * Get the relevant mime object. * - * @param mediaTypeEntry - Media type entry - * @param ballerinaUtilGenerator - Ballerina util generator - * @param imports - Ballerina imports + * @param mediaTypeEntry - Media type entry + * @param ballerinaUtilGenerator - Ballerina util generator + * @param imports - Ballerina imports * @return mimetype * @throws BallerinaOpenApiException throws an exception on unsupported mime types. */ public MimeType getMimeType(Map.Entry mediaTypeEntry, BallerinaUtilGenerator ballerinaUtilGenerator, List imports) throws BallerinaOpenApiException { + Schema requestBodySchema = mediaTypeEntry.getValue().getSchema(); - if (requestBodySchema != null && (requestBodySchema.get$ref() != null || requestBodySchema.getType() != null + if (requestBodySchema != null && (requestBodySchema.get$ref() != null || + GeneratorUtils.getOpenAPIType(requestBodySchema) != null || requestBodySchema.getProperties() != null)) { String mediaType = mediaTypeEntry.getKey(); - if (mediaType.contains(VENDOR_SPECIFIC_TYPE)) { - return new CustomType(); - } else if (mediaType.contains(JSON)) { + if (mediaType.matches(".*/json") || mediaType.matches("application/.*\\+json")) { return new JsonType(); } else if (mediaType.startsWith(TEXT_PREFIX) || mediaType.contains(PDF) || mediaType.startsWith(IMAGE)) { return new CustomType(); - } else if (mediaType.contains(XML)) { + } else if (mediaType.matches(".*/xml") || mediaType.matches("application/.*\\+xml")) { return new XmlType(imports); } else if (mediaType.equals(APPLICATION_FORM_URLENCODED)) { return new UrlEncodedType(ballerinaUtilGenerator); - } else if (mediaType.equals(APPLICATION_OCTET_STREAM)) { - return new OctedStreamType(); + } else if (mediaType.equals(APPLICATION_OCTET_STREAM) || + mediaType.matches("application/.*\\+octet-stream")) { + return new OctetStreamType(); } else if (mediaType.equals(MULTIPART_FORM_DATA)) { return new MultipartFormData(imports, ballerinaUtilGenerator); - } else if (mediaType.contains(ANY_TYPE)) { - return new AnyType(); + } else if (mediaType.contains(VENDOR_SPECIFIC_TYPE)) { + return new CustomType(); } else { throw new BallerinaOpenApiException(String.format(UNSUPPORTED_MEDIA_ERROR, mediaType)); } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/AnyType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/AnyType.java similarity index 78% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/AnyType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/AnyType.java index 06e83cde3..84fd3b1f0 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/AnyType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/AnyType.java @@ -1,26 +1,26 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; import io.ballerina.compiler.syntax.tree.StatementNode; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; import io.swagger.v3.oas.models.media.MediaType; import java.util.List; @@ -29,7 +29,7 @@ /** * Defines payload that supports all types structure. * - * @since 2.0.0 + * @since 1.3.0 */ public class AnyType extends MimeType { diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/CustomType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/CustomType.java similarity index 68% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/CustomType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/CustomType.java index 94d4d61ab..89790a520 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/CustomType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/CustomType.java @@ -1,24 +1,25 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.openapi.core.GeneratorConstants; import io.swagger.v3.oas.models.media.MediaType; import java.util.List; @@ -27,11 +28,12 @@ /** * Defines vendor specific payload mime type. * - * @since 2.0.0 + * @since 1.3.0 */ public class CustomType extends MimeType { + @Override public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { - setPayload(statementsList, payloadName, mediaTypeEntry.getKey()); + setPayload(statementsList, GeneratorConstants.PAYLOAD, mediaTypeEntry.getKey()); } } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/JsonType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/JsonType.java similarity index 74% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/JsonType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/JsonType.java index c4595434b..9ff9ef408 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/JsonType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/JsonType.java @@ -1,26 +1,26 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.StatementNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; import io.swagger.v3.oas.models.media.MediaType; import java.util.List; @@ -29,15 +29,15 @@ /** * Defines the payload structure of json mime type. * - * @since 2.0.0 + * @since 1.3.0 */ public class JsonType extends MimeType { @Override public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { - payloadName = "jsonBody"; + String payloadName = "jsonBody"; VariableDeclarationNode jsonVariable = GeneratorUtils.getSimpleStatement("json", payloadName - , "check payload.cloneWithType(json)"); + , "payload.toJson()"); statementsList.add(jsonVariable); setPayload(statementsList, payloadName, mediaTypeEntry.getKey()); } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MimeType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MimeType.java similarity index 68% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MimeType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MimeType.java index c9d569d5d..bded491be 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MimeType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MimeType.java @@ -1,56 +1,52 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; import io.ballerina.compiler.syntax.tree.StatementNode; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; import io.swagger.v3.oas.models.media.MediaType; import java.util.List; import java.util.Map; -import static io.ballerina.openapi.generators.GeneratorConstants.PAYLOAD; - /** * Abstract class that defines the mime type. * - * @since 2.0.0 + * @since 1.3.0 */ public abstract class MimeType { - String payloadName = PAYLOAD; - /** * Generate statements of defining structure and setting payload. * - * @param statementsList - Previous statements list - * @param mediaTypeEntry - Media type entry + * @param statementsList - Previous statements list + * @param mediaTypeEntry - Media type entry */ public abstract void setPayload(List statementsList, Map.Entry mediaTypeEntry); /** * Generate statements for setting payload in the request. * - * @param statementsList - Previous statements list - * @param payloadName - Payload name - * @param mediaType - Media type + * @param statementsList - Previous statements list + * @param payloadName - Payload name + * @param mediaType - Media type */ public void setPayload(List statementsList, String payloadName, String mediaType) { ExpressionStatementNode setPayloadExpression = GeneratorUtils.getSimpleExpressionStatementNode( diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MultipartFormData.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MultipartFormData.java similarity index 85% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MultipartFormData.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MultipartFormData.java index f08bb123a..e508a9f09 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/MultipartFormData.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/MultipartFormData.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; @@ -33,13 +33,14 @@ import io.ballerina.compiler.syntax.tree.StatementNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaUtilGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.generators.client.BallerinaUtilGenerator; import io.swagger.v3.oas.models.headers.Header; import io.swagger.v3.oas.models.media.Encoding; import io.swagger.v3.oas.models.media.MediaType; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -62,13 +63,15 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.MIME; -import static io.ballerina.openapi.generators.GeneratorUtils.addImport; -import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorConstants.MIME; +import static io.ballerina.openapi.core.GeneratorUtils.addImport; +import static io.ballerina.openapi.core.GeneratorUtils.escapeIdentifier; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; /** * Defines the payload structure of multipart form-data mime type. + * + * @since 1.3.0 */ public class MultipartFormData extends MimeType { @@ -105,29 +108,33 @@ public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { if (mediaTypeEntry.getValue().getEncoding() != null) { - List filedOfMap = new ArrayList<>(); + List mapFields = new LinkedList<>(); BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("map")); CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( createIdentifierToken("encodingMap")); TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); - Set> endcodingEntries = mediaTypeEntry.getValue().getEncoding().entrySet(); - for (Map.Entry entry : endcodingEntries) { - getEncoding(entry, filedOfMap); + Set> encodingEntries = mediaTypeEntry.getValue().getEncoding().entrySet(); + for (Map.Entry entry : encodingEntries) { + getEncoding(entry, mapFields); + } + + if (mapFields.isEmpty()) { + return null; } - filedOfMap.remove(filedOfMap.size() - 1); + mapFields.remove(mapFields.size() - 1); MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( - createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(filedOfMap), createToken(CLOSE_BRACE_TOKEN)); + createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(mapFields), createToken(CLOSE_BRACE_TOKEN)); return createVariableDeclarationNode(createEmptyNodeList(), null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, createToken(SEMICOLON_TOKEN)); - } + return null; } - private void getEncoding(Map.Entry entry, List filedOfMap) { + private void getEncoding(Map.Entry entry, List mapFields) { SpecificFieldNode contentField = null; SpecificFieldNode headersField = null; IdentifierToken fieldName = createIdentifierToken('"' + entry.getKey() + '"'); @@ -141,7 +148,7 @@ private void getEncoding(Map.Entry entry, List filedOfMa } if (entry.getValue().getHeaders() != null) { - headersField = getHeaderEncoding(entry); + headersField = getHeaderEncoding(entry); } if (headersField != null && contentField != null) { @@ -156,8 +163,8 @@ private void getEncoding(Map.Entry entry, List filedOfMa createToken(OPEN_BRACE_TOKEN), separatedNodeList, createToken(CLOSE_BRACE_TOKEN)); SpecificFieldNode specificFieldNode = createSpecificFieldNode(null, fieldName, createToken(COLON_TOKEN), expressionNode); - filedOfMap.add(specificFieldNode); - filedOfMap.add(createToken(COMMA_TOKEN)); + mapFields.add(specificFieldNode); + mapFields.add(createToken(COMMA_TOKEN)); } private SpecificFieldNode getHeaderEncoding(Map.Entry entry) { @@ -171,7 +178,9 @@ private SpecificFieldNode getHeaderEncoding(Map.Entry entry) { headerMap.add(specificFieldNode); headerMap.add(createToken(COMMA_TOKEN)); } - headerMap.remove(headerMap.size() - 1); + if (!headerMap.isEmpty()) { + headerMap.remove(headerMap.size() - 1); + } MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(headerMap), createToken(CLOSE_BRACE_TOKEN)); diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/OctedStreamType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/OctetStreamType.java similarity index 63% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/OctedStreamType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/OctetStreamType.java index 76f039003..55ac41203 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/OctedStreamType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/OctetStreamType.java @@ -1,43 +1,48 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.StatementNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.Schema; import java.util.List; import java.util.Map; -import static io.ballerina.openapi.generators.GeneratorConstants.BYTE; - +import static io.ballerina.openapi.core.GeneratorConstants.BYTE; /** * Defines the payload structure of "application/octet-stream" mime type. * - * @since 2.0.0 + * @since 1.3.0 */ -public class OctedStreamType extends MimeType { +public class OctetStreamType extends MimeType { + @Override public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { - if (mediaTypeEntry.getValue().getSchema().getFormat().equals(BYTE)) { + + String payloadName = GeneratorConstants.PAYLOAD; + Schema mediaTypeSchema = mediaTypeEntry.getValue().getSchema(); + if (mediaTypeSchema.getFormat() != null && mediaTypeSchema.getFormat().equals(BYTE)) { payloadName = "encodedRequestBody"; VariableDeclarationNode encodedVariable = GeneratorUtils.getSimpleStatement("string", payloadName, "payload.toBase64()"); diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/UrlEncodedType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/UrlEncodedType.java similarity index 87% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/UrlEncodedType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/UrlEncodedType.java index d02b1a973..11d4844b4 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/UrlEncodedType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/UrlEncodedType.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; @@ -25,8 +25,8 @@ import io.ballerina.compiler.syntax.tree.StatementNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.client.BallerinaUtilGenerator; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.generators.client.BallerinaUtilGenerator; import io.swagger.v3.oas.models.media.Encoding; import io.swagger.v3.oas.models.media.MediaType; @@ -47,16 +47,17 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.ENCODING; -import static io.ballerina.openapi.generators.GeneratorConstants.STRING; -import static io.ballerina.openapi.generators.GeneratorUtils.createEncodingMap; +import static io.ballerina.openapi.core.GeneratorConstants.ENCODING; +import static io.ballerina.openapi.core.GeneratorConstants.STRING; +import static io.ballerina.openapi.core.GeneratorUtils.createEncodingMap; /** * Defines the payload structure of "application/x-www-form-urlencoded" mime type. * - * @since 2.0.0 + * @since 1.3.0 */ public class UrlEncodedType extends MimeType { + private final BallerinaUtilGenerator ballerinaUtilGenerator; public UrlEncodedType(BallerinaUtilGenerator ballerinaUtilGenerator) { @@ -65,19 +66,19 @@ public UrlEncodedType(BallerinaUtilGenerator ballerinaUtilGenerator) { @Override public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { + ballerinaUtilGenerator.setRequestBodyEncodingFound(true); VariableDeclarationNode requestBodyEncodingMap = getRequestBodyEncodingMap( mediaTypeEntry.getValue().getEncoding()); - payloadName = "encodedRequestBody"; + String payloadName = "encodedRequestBody"; if (requestBodyEncodingMap != null) { statementsList.add(requestBodyEncodingMap); - VariableDeclarationNode requestBodyVariable = GeneratorUtils.getSimpleStatement(STRING, - payloadName, + VariableDeclarationNode requestBodyVariable = GeneratorUtils.getSimpleStatement(STRING, payloadName, "createFormURLEncodedRequestBody(payload, requestBodyEncoding)"); statementsList.add(requestBodyVariable); } else { - VariableDeclarationNode requestBodyVariable = GeneratorUtils.getSimpleStatement(STRING, - payloadName, "createFormURLEncodedRequestBody(payload)"); + VariableDeclarationNode requestBodyVariable = GeneratorUtils.getSimpleStatement(STRING, payloadName, + "createFormURLEncodedRequestBody(payload)"); statementsList.add(requestBodyVariable); } setPayload(statementsList, payloadName, mediaTypeEntry.getKey()); @@ -96,6 +97,7 @@ public void setPayload(List statementsList, Map.Entry encodingMap) { + List filedOfMap = new ArrayList<>(); BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("map<" + ENCODING + ">")); diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/XmlType.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/XmlType.java similarity index 69% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/XmlType.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/XmlType.java index fca89d5b6..fd639a299 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/client/mime/XmlType.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/mime/XmlType.java @@ -1,54 +1,55 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.client.mime; +package io.ballerina.openapi.core.generators.client.mime; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; import io.ballerina.compiler.syntax.tree.StatementNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorUtils; import io.swagger.v3.oas.models.media.MediaType; import java.util.List; import java.util.Map; -import static io.ballerina.openapi.generators.GeneratorConstants.XML_DATA; -import static io.ballerina.openapi.generators.GeneratorUtils.addImport; +import static io.ballerina.openapi.core.GeneratorConstants.XML_DATA; +import static io.ballerina.openapi.core.GeneratorUtils.addImport; /** * Defines the payload structure of xml mime type. * - * @since 2.0.0 + * @since 1.3.0 */ public class XmlType extends MimeType { - private List imports; + + private final List imports; public XmlType(List imports) { - this.imports = imports; + this.imports = imports; } @Override public void setPayload(List statementsList, Map.Entry mediaTypeEntry) { - payloadName = "xmlBody"; + String payloadName = "xmlBody"; addImport(imports, XML_DATA); - VariableDeclarationNode jsonVariable = GeneratorUtils.getSimpleStatement("json", - "jsonBody", "check payload.cloneWithType(json)"); + VariableDeclarationNode jsonVariable = GeneratorUtils.getSimpleStatement("json", "jsonBody", + "payload.toJson()"); statementsList.add(jsonVariable); VariableDeclarationNode xmlBody = GeneratorUtils.getSimpleStatement("xml?", payloadName, "check xmldata:fromJson(jsonBody)"); diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/model/OASClientConfig.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/model/OASClientConfig.java new file mode 100644 index 000000000..5875cc2bb --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/client/model/OASClientConfig.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.client.model; + +import io.ballerina.openapi.core.model.Filter; +import io.swagger.v3.oas.models.OpenAPI; + +/** + * This class stores metadata that related to client code generations. + * + * @since 1.3.0 + */ +public class OASClientConfig { + private final OpenAPI openAPI; + private final Filter filters; + private final boolean nullable; + private final boolean resourceMode; + private final boolean isPlugin; + + + private OASClientConfig(Builder clientConfigBuilder) { + this.openAPI = clientConfigBuilder.openAPI; + this.filters = clientConfigBuilder.filters; + this.nullable = clientConfigBuilder.nullable; + this.isPlugin = clientConfigBuilder.isPlugin; + this.resourceMode = clientConfigBuilder.resourceMode; + } + + public OpenAPI getOpenAPI() { + return openAPI; + } + + public Filter getFilters() { + return filters; + } + + public boolean isNullable() { + return nullable; + } + + public boolean isResourceMode() { + return resourceMode; + } + + public boolean isPlugin() { + return isPlugin; + } + + /** + * Client IDL plugin meta data builder class. + */ + public static class Builder { + private OpenAPI openAPI; + private Filter filters; + private boolean nullable = false; + private boolean resourceMode = true; + private boolean isPlugin = false; + + public Builder withOpenAPI(OpenAPI openAPI) { + this.openAPI = openAPI; + return this; + } + + public Builder withFilters(Filter filters) { + this.filters = filters; + return this; + } + + public Builder withNullable(boolean nullable) { + this.nullable = nullable; + return this; + } + + public Builder withResourceMode(boolean resourceMode) { + this.resourceMode = resourceMode; + return this; + } + + public Builder withPlugin(boolean isPlugin) { + this.isPlugin = isPlugin; + return this; + } + + public OASClientConfig build() { + return new OASClientConfig(this); + } + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/DocCommentsGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/document/DocCommentsGenerator.java similarity index 73% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/DocCommentsGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/document/DocCommentsGenerator.java index 05bbabd86..1ce909d56 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/DocCommentsGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/document/DocCommentsGenerator.java @@ -1,33 +1,40 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators; +package io.ballerina.openapi.core.generators.document; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.BasicLiteralNode; 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.ModuleMemberDeclarationNode; import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeParser; import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.SpecificFieldNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -57,25 +64,25 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_LITERAL; -import static io.ballerina.openapi.generators.GeneratorConstants.X_BALLERINA_DEPRECATED_REASON; -import static io.ballerina.openapi.generators.GeneratorConstants.X_BALLERINA_DISPLAY; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_END_OF_LINE_MINUTIAE; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; /** * This class util for maintain the API doc comment related functions. + * + * @since 1.3.0 */ public class DocCommentsGenerator { + /** * Extract extension for find the display annotation. * - * @param extensions OpenAPI extension. - * */ + * @param extensions OpenAPI extension. + */ public static void extractDisplayAnnotation(Map extensions, - List annotationNodes) { + List annotationNodes) { + if (extensions != null) { - for (Map.Entry extension: extensions.entrySet()) { - if (extension.getKey().trim().equals(X_BALLERINA_DISPLAY)) { + for (Map.Entry extension : extensions.entrySet()) { + if (extension.getKey().trim().equals(GeneratorConstants.X_BALLERINA_DISPLAY)) { annotationNodes.add(getAnnotationNode(extension)); } } @@ -85,12 +92,13 @@ public static void extractDisplayAnnotation(Map extensions, /** * Extract annotation and documentation related for deprecated records and schemas. * - * @param extensions OpenAPI extensions - * @param documentation List of documentation nodes to be updated with documentation related to deprecation - * @param annotationNodes List of annotation nodes to be updated with deprecated annotation + * @param extensions OpenAPI extensions + * @param documentation List of documentation nodes to be updated with documentation related to deprecation + * @param annotationNodes List of annotation nodes to be updated with deprecated annotation */ public static void extractDeprecatedAnnotation(Map extensions, List documentation, List annotationNodes) { + AnnotationNode deprecatedAnnotation = createAnnotationNode(createToken(AT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("deprecated")), null); if (documentation.size() > 0) { @@ -98,7 +106,7 @@ public static void extractDeprecatedAnnotation(Map extensions, L "\n# Deprecated", false)); if (extensions != null && extensions.entrySet().size() > 0) { for (Map.Entry next : extensions.entrySet()) { - if (next.getKey().equals(X_BALLERINA_DEPRECATED_REASON)) { + if (next.getKey().equals(GeneratorConstants.X_BALLERINA_DEPRECATED_REASON)) { documentation.addAll(DocCommentsGenerator.createAPIDescriptionDoc( next.getValue().toString(), false)); } @@ -113,7 +121,7 @@ private static AnnotationNode getAnnotationNode(Map.Entry extens LinkedHashMap extFields = (LinkedHashMap) extension.getValue(); List annotFields = new ArrayList<>(); if (!extFields.isEmpty()) { - for (Map.Entry field: extFields.entrySet()) { + for (Map.Entry field : extFields.entrySet()) { BasicLiteralNode valueExpr = createBasicLiteralNode(STRING_LITERAL, createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, @@ -140,17 +148,18 @@ private static AnnotationNode getAnnotationNode(Map.Entry extens , annotateReference, annotValue); } - public static List createAPIDescriptionDoc( - String description, boolean addExtraLine) { + 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(), SINGLE_WS_MINUTIAE); + 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(), - SINGLE_END_OF_LINE_MINUTIAE))); + GeneratorUtils.SINGLE_END_OF_LINE_MINUTIAE))); documentElements.add(documentationLineNode); } if (addExtraLine) { @@ -161,6 +170,24 @@ public static List createAPIDescriptionDoc( return documentElements; } + public static MarkdownDocumentationNode createAPIParamDocFromSring(String paramName, String description) { + String[] paramDescriptionLines = description.split("\n"); + StringBuilder docComment = new StringBuilder("# + " + paramName + " - " + + paramDescriptionLines[0] + System.lineSeparator()); + for (int i = 1; i < paramDescriptionLines.length; i++) { + String line = paramDescriptionLines[i].replaceAll("[\\r\\n\\t]", ""); + if (!line.isBlank()) { + docComment.append("# ").append(line).append(System.lineSeparator()); + } + } + docComment.append(System.lineSeparator()).append("type a A;"); + ModuleMemberDeclarationNode moduleMemberDeclarationNode = + NodeParser.parseModuleMemberDeclaration(docComment.toString()); + TypeDefinitionNode typeDefinitionNode = (TypeDefinitionNode) moduleMemberDeclarationNode; + MetadataNode metadataNode = typeDefinitionNode.metadata().get(); + return (MarkdownDocumentationNode) metadataNode.children().get(0); + } + public static MarkdownParameterDocumentationLineNode createAPIParamDoc(String paramName, String description) { String[] paramDescriptionLines = description.split("\n"); List documentElements = new ArrayList<>(); diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaTypesGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/BallerinaTypesGenerator.java similarity index 52% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaTypesGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/BallerinaTypesGenerator.java index 5d23852db..d4808e644 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaTypesGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/BallerinaTypesGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema; +package io.ballerina.openapi.core.generators.schema; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.AnnotationNode; @@ -27,20 +27,22 @@ 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.QualifiedNameReferenceNode; 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.compiler.syntax.tree.TypeReferenceNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.GeneratorUtils; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.RecordTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.TypeGenerator; -import io.ballerina.openapi.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.TypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; import io.swagger.v3.oas.models.Components; @@ -48,24 +50,41 @@ import io.swagger.v3.oas.models.media.Schema; 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.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; import static io.ballerina.openapi.converter.Constants.HTTP; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.hasConstraints; -import static io.ballerina.openapi.generators.GeneratorUtils.isValidSchemaName; +import static io.ballerina.openapi.core.GeneratorConstants.CONNECTION_CONFIG; /** * This class wraps the {@link Schema} from openapi models inorder to overcome complications * while populating syntax tree. + * + * @since 1.3.0 */ public class BallerinaTypesGenerator { - private List typeDefinitionNodeList; - private boolean hasConstraints; + + private final List typeDefinitionNodeList; + private final Set imports = new LinkedHashSet<>(); + + /** + * This public constructor is used to generate record and other relevant data type when the nullable flag is + * enabled in the openapi command. + * + * @param openAPI OAS definition + * @param isNullable nullable value + * @param typeDefinitionNodeList list of types generated by earlier generations + */ + public BallerinaTypesGenerator(OpenAPI openAPI, boolean isNullable, + List typeDefinitionNodeList) { + GeneratorMetaData.createInstance(openAPI, isNullable, false); + this.typeDefinitionNodeList = typeDefinitionNodeList; + } /** * This public constructor is used to generate record and other relevant data type when the nullable flag is @@ -75,9 +94,7 @@ public class BallerinaTypesGenerator { * @param isNullable nullable value */ public BallerinaTypesGenerator(OpenAPI openAPI, boolean isNullable) { - GeneratorMetaData.createInstance(openAPI, isNullable); - this.typeDefinitionNodeList = new LinkedList<>(); - this.hasConstraints = false; + this(openAPI, isNullable, new LinkedList<>()); } /** @@ -87,14 +104,21 @@ public BallerinaTypesGenerator(OpenAPI openAPI, boolean isNullable) { * @param openAPI OAS definition */ public BallerinaTypesGenerator(OpenAPI openAPI) { - this(openAPI, false); - GeneratorMetaData.createInstance(openAPI, false); + this(openAPI, false, new LinkedList<>()); } /** - * Set the typeDefinitionNodeList. + * This public constructor is used to generate record and other relevant data type when the nullable flag is + * enabled in the openapi command. + * + * @param openAPI OAS definition + * @param isNullable nullable value + * @param typeDefinitionNodeList list of types generated by earlier generations + * @param generateServiceType indicate whether the service generation includes service type */ - public void setTypeDefinitionNodeList(List typeDefinitionNodeList) { + public BallerinaTypesGenerator(OpenAPI openAPI, boolean isNullable, List typeDefinitionNodeList, + boolean generateServiceType) { + GeneratorMetaData.createInstance(openAPI, isNullable, generateServiceType); this.typeDefinitionNodeList = typeDefinitionNodeList; } @@ -111,13 +135,10 @@ public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { if (schemas != null) { for (Map.Entry schema : schemas.entrySet()) { String schemaKey = schema.getKey().trim(); - if (!hasConstraints) { - hasConstraints = hasConstraints(schema.getValue()); - } - if (isValidSchemaName(schemaKey)) { + if (GeneratorUtils.isValidSchemaName(schemaKey)) { List schemaDoc = new ArrayList<>(); - typeDefinitionNodeListForSchema.add(getTypeDefinitionNode - (schema.getValue(), schemaKey, schemaDoc)); + typeDefinitionNodeListForSchema.add(getTypeDefinitionNode(schema.getValue(), schemaKey, + schemaDoc)); } } } @@ -138,28 +159,35 @@ public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { } private NodeList generateImportNodes() { - List imports = new ArrayList<>(); + Set importDeclarationNodes = new LinkedHashSet<>(); + // Imports for the http module, when record has http type inclusions. if (!typeDefinitionNodeList.isEmpty()) { - importsForTypeDefinitions(imports); + importsForTypeDefinitions(importDeclarationNodes); } - if (hasConstraints) { - //import for constraint - ImportDeclarationNode importForConstraint = GeneratorUtils.getImportDeclarationNode( - GeneratorConstants.BALLERINA, - GeneratorConstants.CONSTRAINT); - imports.add(importForConstraint); + //Imports for constraints + if (!imports.isEmpty()) { + for (String importValue : imports) { + ImportDeclarationNode importDeclarationNode = NodeParser.parseImportDeclaration(importValue); + importDeclarationNodes.add(importDeclarationNode); + } } - if (imports.isEmpty()) { + if (importDeclarationNodes.isEmpty()) { return createEmptyNodeList(); } - return createNodeList(imports); + return createNodeList(importDeclarationNodes); } - private void importsForTypeDefinitions(List imports) { - for (TypeDefinitionNode node: typeDefinitionNodeList) { + private void importsForTypeDefinitions(Set imports) { + for (TypeDefinitionNode node : typeDefinitionNodeList) { if (!(node.typeDescriptor() instanceof RecordTypeDescriptorNode)) { continue; } + if (node.typeName().text().equals(CONNECTION_CONFIG)) { + ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( + GeneratorConstants.BALLERINA, + HTTP); + imports.add(importForHttp); + } RecordTypeDescriptorNode record = (RecordTypeDescriptorNode) node.typeDescriptor(); for (Node field : record.fields()) { if (!(field instanceof TypeReferenceNode) || @@ -168,7 +196,10 @@ private void importsForTypeDefinitions(List imports) { } TypeReferenceNode recordField = (TypeReferenceNode) field; QualifiedNameReferenceNode typeInclusion = (QualifiedNameReferenceNode) recordField.typeName(); - if (typeInclusion.modulePrefix().text().equals(HTTP)) { + boolean isHttpImportExist = imports.stream().anyMatch(importNode -> importNode.moduleName().stream() + .anyMatch(moduleName -> moduleName.text().equals(HTTP))); + + if (!isHttpImportExist && typeInclusion.modulePrefix().text().equals(HTTP)) { ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( GeneratorConstants.BALLERINA, GeneratorConstants.HTTP); @@ -189,29 +220,53 @@ private void importsForTypeDefinitions(List imports) { */ public TypeDefinitionNode getTypeDefinitionNode(Schema schema, String typeName, List schemaDocs) throws BallerinaOpenApiException { - IdentifierToken typeNameToken = AbstractNodeFactory.createIdentifierToken(getValidName( + IdentifierToken typeNameToken = AbstractNodeFactory.createIdentifierToken(GeneratorUtils.getValidName( typeName.trim(), true)); - TypeGenerator typeGenerator = TypeGeneratorUtils.getTypeGenerator(schema, getValidName( + TypeGenerator typeGenerator = TypeGeneratorUtils.getTypeGenerator(schema, GeneratorUtils.getValidName( typeName.trim(), true), null); List typeAnnotations = new ArrayList<>(); - AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(schema); - if (constraintNode != null) { - typeAnnotations.add(constraintNode); + if (TypeGeneratorUtils.isConstraintAllowed(typeName, schema)) { + AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(typeName, schema); + if (constraintNode != null) { + typeAnnotations.add(constraintNode); + } } TypeGeneratorUtils.getRecordDocs(schemaDocs, schema, typeAnnotations); TypeDefinitionNode typeDefinitionNode = typeGenerator.generateTypeDefinitionNode(typeNameToken, schemaDocs, typeAnnotations); - if (typeGenerator instanceof ArrayTypeGenerator && - ((ArrayTypeGenerator) typeGenerator).getArrayItemWithConstraint() != null) { - typeDefinitionNodeList.add(((ArrayTypeGenerator) typeGenerator).getArrayItemWithConstraint()); + if (typeGenerator instanceof ArrayTypeGenerator && !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); } else if (typeGenerator instanceof RecordTypeGenerator && - !((RecordTypeGenerator) typeGenerator).getTypeDefinitionNodeList().isEmpty()) { - typeDefinitionNodeList.addAll(((RecordTypeGenerator) typeGenerator).getTypeDefinitionNodeList()); - } else if (typeGenerator instanceof AllOfRecordTypeGenerator && - !((AllOfRecordTypeGenerator) typeGenerator).getTypeDefinitionNodeList().isEmpty()) { - typeDefinitionNodeList.addAll(((RecordTypeGenerator) typeGenerator).getTypeDefinitionNodeList()); + !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; } + + /** + * Remove duplicate of the 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); + } + } + } } diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/TypeGeneratorUtils.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/TypeGeneratorUtils.java similarity index 51% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/TypeGeneratorUtils.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/TypeGeneratorUtils.java index db9cf8508..ee7239c02 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/TypeGeneratorUtils.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/TypeGeneratorUtils.java @@ -1,27 +1,28 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema; +package io.ballerina.openapi.core.generators.schema; 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; @@ -29,37 +30,39 @@ 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.OptionalTypeDescriptorNode; 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 io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.DocCommentsGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.AnyDataTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.PrimitiveTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.RecordTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.ReferencedTypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.TypeGenerator; -import io.ballerina.openapi.generators.schema.ballerinatypegenerators.UnionTypeGenerator; -import io.ballerina.openapi.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.AnyDataTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.PrimitiveTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.ReferencedTypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.TypeGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.internal.regexp.RegExpFactory; import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.IntegerSchema; -import io.swagger.v3.oas.models.media.NumberSchema; -import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.media.StringSchema; +import org.apache.commons.lang3.tuple.ImmutablePair; +import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; @@ -70,69 +73,61 @@ 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.NodeFactory.createUnionTypeDescriptorNode; 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.PIPE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.BOOLEAN; -import static io.ballerina.openapi.generators.GeneratorConstants.CLOSE_BRACE; -import static io.ballerina.openapi.generators.GeneratorConstants.COLON; -import static io.ballerina.openapi.generators.GeneratorConstants.COMMA; -import static io.ballerina.openapi.generators.GeneratorConstants.CONSTRAINT_ARRAY; -import static io.ballerina.openapi.generators.GeneratorConstants.CONSTRAINT_FLOAT; -import static io.ballerina.openapi.generators.GeneratorConstants.CONSTRAINT_INT; -import static io.ballerina.openapi.generators.GeneratorConstants.CONSTRAINT_NUMBER; -import static io.ballerina.openapi.generators.GeneratorConstants.CONSTRAINT_STRING; -import static io.ballerina.openapi.generators.GeneratorConstants.EXCLUSIVE_MAX; -import static io.ballerina.openapi.generators.GeneratorConstants.EXCLUSIVE_MIN; -import static io.ballerina.openapi.generators.GeneratorConstants.FLOAT; -import static io.ballerina.openapi.generators.GeneratorConstants.INTEGER; -import static io.ballerina.openapi.generators.GeneratorConstants.MAXIMUM; -import static io.ballerina.openapi.generators.GeneratorConstants.MAX_LENGTH; -import static io.ballerina.openapi.generators.GeneratorConstants.MINIMUM; -import static io.ballerina.openapi.generators.GeneratorConstants.MIN_LENGTH; -import static io.ballerina.openapi.generators.GeneratorConstants.NUMBER; -import static io.ballerina.openapi.generators.GeneratorConstants.OBJECT; -import static io.ballerina.openapi.generators.GeneratorConstants.OPEN_BRACE; -import static io.ballerina.openapi.generators.GeneratorConstants.STRING; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA; +import static io.ballerina.openapi.core.GeneratorConstants.CONSTRAINT; +import static io.ballerina.openapi.core.GeneratorConstants.DECIMAL; +import static io.ballerina.openapi.core.GeneratorConstants.FLOAT; +import static io.ballerina.openapi.core.GeneratorConstants.INT; +import static io.ballerina.openapi.core.GeneratorConstants.INT_SIGNED32; +import static io.ballerina.openapi.core.GeneratorConstants.NULL; +import static io.ballerina.openapi.core.GeneratorConstants.STRING; +import static io.ballerina.openapi.core.GeneratorUtils.convertOpenAPITypeToBallerina; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIType; /** * Contains util functions needed for schema generation. * - * @since 2.0.0 + * @since 1.3.0 */ public class TypeGeneratorUtils { - private static final List primitiveTypeList = - new ArrayList<>(Arrays.asList(INTEGER, NUMBER, STRING, BOOLEAN)); + public static final List PRIMITIVE_TYPE_LIST = + Collections.unmodifiableList(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 + * @param typeName parameter name * @return Relevant SchemaType object */ public static TypeGenerator getTypeGenerator(Schema schemaValue, String typeName, String parentName) { + if (schemaValue.get$ref() != null) { return new ReferencedTypeGenerator(schemaValue, typeName); - } else if (schemaValue instanceof ComposedSchema) { - ComposedSchema composedSchema = (ComposedSchema) schemaValue; - if (composedSchema.getAllOf() != null) { + } else if (GeneratorUtils.isComposedSchema(schemaValue)) { + if (schemaValue.getAllOf() != null) { return new AllOfRecordTypeGenerator(schemaValue, typeName); } else { return new UnionTypeGenerator(schemaValue, typeName); } - } else if ((schemaValue.getType() != null && schemaValue.getType().equals(OBJECT)) || - schemaValue instanceof ObjectSchema || schemaValue.getProperties() != null) { + } else if ((GeneratorUtils.getOpenAPIType(schemaValue) != null && + GeneratorUtils.getOpenAPIType(schemaValue).equals(GeneratorConstants.OBJECT)) || + GeneratorUtils.isObjectSchema(schemaValue) || schemaValue.getProperties() != null || + GeneratorUtils.isMapSchema(schemaValue)) { return new RecordTypeGenerator(schemaValue, typeName); - } else if (schemaValue instanceof ArraySchema) { + } else if (GeneratorUtils.isArraySchema(schemaValue)) { return new ArrayTypeGenerator(schemaValue, typeName, parentName); - } else if (schemaValue.getType() != null && primitiveTypeList.contains(schemaValue.getType())) { + } else if (GeneratorUtils.getOpenAPIType(schemaValue) != null && + PRIMITIVE_TYPE_LIST.contains(GeneratorUtils.getOpenAPIType(schemaValue))) { return new PrimitiveTypeGenerator(schemaValue, typeName); } else { // when schemaValue.type == null return new AnyDataTypeGenerator(schemaValue, typeName); @@ -148,7 +143,7 @@ public static TypeGenerator getTypeGenerator(Schema schemaValue, String typeN * Scenario 5 : schema.getNullable() == null && nullable == true -> string? * Scenario 6 : schema.getNullable() == null && nullable == false -> string * - * @param schema Schema of the property + * @param schema Schema of the property * @param originalTypeDesc Type name * @return Final type of the field */ @@ -159,25 +154,52 @@ public static TypeDescriptorNode getNullableType(Schema schema, TypeDescriptorNo if (schema.getNullable()) { nillableType = createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); } + } else if (schema.getTypes() != null && schema.getTypes().contains(NULL)) { + nillableType = createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); } else if (nullable) { nillableType = createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); } return nillableType; } + /** + * This function returns record field list with its relevant imports as set of string. + * Ex: If the record field has a constraint annotation node, then the type.bal needs its constraint imports + * therefore this function makes sure to add relevant imports to the type.bal. + */ + public static ImmutablePair, Set> updateRecordFieldListWithImports( + List required, List recordFieldList, Map.Entry> field, + Schema fieldSchema, NodeList schemaDocNodes, IdentifierToken fieldName, + TypeDescriptorNode fieldTypeName) throws BallerinaOpenApiException { + + return updateRecordFieldListWithImports(required, recordFieldList, field, fieldSchema, schemaDocNodes, + fieldName, + fieldTypeName, System.err); + } - public static void updateRecordFieldList(List required, - List recordFieldList, - Map.Entry field, - Schema fieldSchema, - NodeList schemaDocNodes, - IdentifierToken fieldName, - TypeDescriptorNode fieldTypeName) { + public static ImmutablePair, Set> updateRecordFieldListWithImports( + List required, List recordFieldList, Map.Entry> field, + Schema fieldSchema, NodeList schemaDocNodes, IdentifierToken fieldName, + TypeDescriptorNode fieldTypeName, PrintStream outStream) throws BallerinaOpenApiException { MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(schemaDocNodes); + Set imports = new HashSet<>(); //Generate constraint annotation. - AnnotationNode constraintNode = generateConstraintNode(fieldSchema); + AnnotationNode constraintNode = generateConstraintNode(fieldName.text(), fieldSchema); MetadataNode metadataNode; + boolean isConstraintSupport = + constraintNode != null && fieldSchema.getNullable() != null && fieldSchema.getNullable() || + ((fieldSchema.getOneOf() != null || + fieldSchema.getAnyOf() != null)); + boolean nullable = GeneratorMetaData.getInstance().isNullable(); + if (nullable) { + constraintNode = null; + } else if (isConstraintSupport) { + outStream.printf("WARNING: constraints in the OpenAPI contract will be ignored for the " + + "field `%s`, as constraints are not supported on Ballerina union types%n", + fieldName.toString().trim()); + constraintNode = null; + } if (constraintNode == null) { metadataNode = createMetadataNode(documentationNode, createEmptyNodeList()); } else { @@ -191,10 +213,16 @@ public static void updateRecordFieldList(List required, 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, + Map.Entry> field, Schema fieldSchema, IdentifierToken fieldName, TypeDescriptorNode fieldTypeName, @@ -223,19 +251,27 @@ private static RecordFieldWithDefaultValueNode getRecordFieldWithDefaultValueNod TypeDescriptorNode fieldTypeName, MetadataNode metadataNode) { - Token defaultValue; - if (fieldSchema instanceof StringSchema) { - if (fieldSchema.getDefault().toString().trim().equals("\"")) { - defaultValue = AbstractNodeFactory.createIdentifierToken("\"" + "\\" + + Token defaultValueToken; + String defaultValue = fieldSchema.getDefault().toString().trim(); + if (GeneratorUtils.isStringSchema(fieldSchema)) { + if (defaultValue.equals("\"")) { + defaultValueToken = AbstractNodeFactory.createIdentifierToken("\"" + "\\" + fieldSchema.getDefault().toString() + "\""); } else { - defaultValue = AbstractNodeFactory.createIdentifierToken("\"" + + defaultValueToken = AbstractNodeFactory.createIdentifierToken("\"" + fieldSchema.getDefault().toString() + "\""); } + } else if (!defaultValue.matches("^[0-9]*$") && !defaultValue.matches("^(\\d*\\.)?\\d+$") + && !(defaultValue.startsWith("[") && defaultValue.endsWith("]")) && + !GeneratorUtils.isBooleanSchema(fieldSchema)) { + //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().toString() + "\""); } else { - defaultValue = AbstractNodeFactory.createIdentifierToken(fieldSchema.getDefault().toString()); + defaultValueToken = AbstractNodeFactory.createIdentifierToken(fieldSchema.getDefault().toString()); } - ExpressionNode expressionNode = createRequiredExpressionNode(defaultValue); + ExpressionNode expressionNode = createRequiredExpressionNode(defaultValueToken); return NodeFactory.createRecordFieldWithDefaultValueNode (metadataNode, null, fieldTypeName, fieldName, createToken(EQUAL_TOKEN), expressionNode, createToken(SEMICOLON_TOKEN)); @@ -247,41 +283,65 @@ private static RecordFieldWithDefaultValueNode getRecordFieldWithDefaultValueNod * @param fieldSchema Schema for data type * @return {@link MetadataNode} */ - public static AnnotationNode generateConstraintNode(Schema fieldSchema) { - if (fieldSchema instanceof StringSchema) { - StringSchema stringSchema = (StringSchema) fieldSchema; - // Attributes : maxLength, minLength - return generateStringConstraint(stringSchema); - } else if (fieldSchema instanceof IntegerSchema || fieldSchema instanceof NumberSchema) { - // Attribute : minimum, maximum, exclusiveMinimum, exclusiveMaximum - return generateNumberConstraint(fieldSchema); - } else if (fieldSchema instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) fieldSchema; - // Attributes: maxItems, minItems - return generateArrayConstraint(arraySchema); + public static AnnotationNode generateConstraintNode(String typeName, Schema fieldSchema) + throws BallerinaOpenApiException { + if (isConstraintAllowed(typeName, fieldSchema)) { + String ballerinaType = convertOpenAPITypeToBallerina(fieldSchema); + // For openAPI field schemas having 'string' type, constraints generation will be skipped when + // the counterpart Ballerina type is non-string (e.g. for string schemas with format 'binary' or 'byte', + // the counterpart ballerina type is 'byte[]', hence any string constraints cannot be applied) + if (ballerinaType.equals(STRING)) { + // Attributes : maxLength, minLength + return generateStringConstraint(fieldSchema); + } else if (ballerinaType.equals(DECIMAL) || ballerinaType.equals(FLOAT) || ballerinaType.equals(INT) || + ballerinaType.equals(INT_SIGNED32)) { + // Attribute : minimum, maximum, exclusiveMinimum, exclusiveMaximum + return generateNumberConstraint(fieldSchema); + } else if (GeneratorUtils.isArraySchema(fieldSchema)) { + // Attributes: maxItems, minItems + return generateArrayConstraint(fieldSchema); + } + // Ignore Object, Map and Composed schemas. + return null; } - // Ignore Object, Map and Composed schemas. return null; } + public static boolean isConstraintAllowed(String typeName, Schema schema) { + + boolean isConstraintNotAllowed = schema.getNullable() != null && schema.getNullable() || + (schema.getOneOf() != null || schema.getAnyOf() != null) || getOpenAPIType(schema) == null; + boolean nullable = GeneratorMetaData.getInstance().isNullable(); + if (nullable) { + return false; + } else if (isConstraintNotAllowed) { + OUT_STREAM.printf("WARNING: constraints in the OpenAPI 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(Schema fieldSchema) { + List fields = getNumberAnnotFields(fieldSchema); if (fields.isEmpty()) { return null; } - String annotBody = OPEN_BRACE + String.join(COMMA, fields) + CLOSE_BRACE; + String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) + + GeneratorConstants.CLOSE_BRACE; AnnotationNode annotationNode; - if (fieldSchema instanceof NumberSchema) { + if (GeneratorUtils.isNumberSchema(fieldSchema)) { if (fieldSchema.getFormat() != null && fieldSchema.getFormat().equals(FLOAT)) { - annotationNode = createAnnotationNode(CONSTRAINT_FLOAT, annotBody); + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_FLOAT, annotBody); } else { - annotationNode = createAnnotationNode(CONSTRAINT_NUMBER, annotBody); + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_NUMBER, annotBody); } } else { - annotationNode = createAnnotationNode(CONSTRAINT_INT, annotBody); + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_INT, annotBody); } return annotationNode; } @@ -289,52 +349,74 @@ private static AnnotationNode generateNumberConstraint(Schema fieldSchema) { /** * Generate constraint for string. */ - private static AnnotationNode generateStringConstraint(StringSchema stringSchema) { + private static AnnotationNode generateStringConstraint(Schema stringSchema) { + List fields = getStringAnnotFields(stringSchema); if (fields.isEmpty()) { return null; } - String annotBody = OPEN_BRACE + String.join(COMMA, fields) + CLOSE_BRACE; - return createAnnotationNode(CONSTRAINT_STRING, annotBody); + 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(ArraySchema arraySchema) { + private static AnnotationNode generateArrayConstraint(Schema arraySchema) { + List fields = getArrayAnnotFields(arraySchema); if (fields.isEmpty()) { return null; } - String annotBody = OPEN_BRACE + String.join(COMMA, fields) + CLOSE_BRACE; - return createAnnotationNode(CONSTRAINT_ARRAY, annotBody); + String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) + + GeneratorConstants.CLOSE_BRACE; + return createAnnotationNode(GeneratorConstants.CONSTRAINT_ARRAY, annotBody); } private static List getNumberAnnotFields(Schema numberSchema) { + List fields = new ArrayList<>(); + boolean isInt = GeneratorUtils.isIntegerSchema(numberSchema); if (numberSchema.getMinimum() != null && numberSchema.getExclusiveMinimum() == null) { String value = numberSchema.getMinimum().toString(); - String fieldRef = MINIMUM + COLON + value; + 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 = MAXIMUM + COLON + value; + String fieldRef = GeneratorConstants.MAXIMUM + GeneratorConstants.COLON + + (isInt ? numberSchema.getMaximum().intValue() : value); fields.add(fieldRef); } if (numberSchema.getExclusiveMinimum() != null && - numberSchema.getExclusiveMinimum() && numberSchema.getMaximum() != null) { + numberSchema.getExclusiveMinimum() && numberSchema.getMinimum() != null) { String value = numberSchema.getMinimum().toString(); - String fieldRef = EXCLUSIVE_MIN + COLON + value; + String fieldRef = GeneratorConstants.EXCLUSIVE_MIN + GeneratorConstants.COLON + + (isInt ? numberSchema.getMinimum().intValue() : value); + fields.add(fieldRef); + } + if (numberSchema.getMinimum() == null && numberSchema.getExclusiveMinimumValue() != null) { + String value = numberSchema.getExclusiveMinimumValue().toString(); + String fieldRef = GeneratorConstants.EXCLUSIVE_MIN + GeneratorConstants.COLON + + (isInt ? numberSchema.getExclusiveMinimumValue().intValue() : value); fields.add(fieldRef); } if (numberSchema.getExclusiveMaximum() != null && - numberSchema.getExclusiveMaximum() && - numberSchema.getMaximum() != null) { + numberSchema.getExclusiveMaximum() && numberSchema.getMaximum() != null) { String value = numberSchema.getMaximum().toString(); - String fieldRef = EXCLUSIVE_MAX + COLON + value; + String fieldRef = GeneratorConstants.EXCLUSIVE_MAX + GeneratorConstants.COLON + + (isInt ? numberSchema.getMaximum().intValue() : value); fields.add(fieldRef); } + if (numberSchema.getMaximum() == null && numberSchema.getExclusiveMaximumValue() != null) { + String value = numberSchema.getExclusiveMaximumValue().toString(); + String fieldRef = GeneratorConstants.EXCLUSIVE_MAX + GeneratorConstants.COLON + + (isInt ? numberSchema.getExclusiveMaximumValue().intValue() : value); + fields.add(fieldRef); + } + //TODO: This will be enable once constraint package gives this support. // if (numberSchema.getMultipleOf() != null) { // String value = numberSchema.getMultipleOf().toString(); @@ -344,37 +426,54 @@ private static List getNumberAnnotFields(Schema numberSchema) { return fields; } - private static List getStringAnnotFields(StringSchema stringSchema) { + private static List getStringAnnotFields(Schema stringSchema) { + List fields = new ArrayList<>(); - if (stringSchema.getMaxLength() != null) { + if (stringSchema.getMaxLength() != null && stringSchema.getMaxLength() != 0) { String value = stringSchema.getMaxLength().toString(); - String fieldRef = MAX_LENGTH + COLON + value; + String fieldRef = GeneratorConstants.MAX_LENGTH + GeneratorConstants.COLON + value; fields.add(fieldRef); } - if (stringSchema.getMinLength() != null) { + if (stringSchema.getMinLength() != null && stringSchema.getMinLength() != 0) { String value = stringSchema.getMinLength().toString(); - String fieldRef = MIN_LENGTH + COLON + value; + String fieldRef = GeneratorConstants.MIN_LENGTH + GeneratorConstants.COLON + value; fields.add(fieldRef); } - //TODO: This will be enable once constraint package gives this support. -// if (stringSchema.getPattern() != null) { -// String value = stringSchema.getPattern(); -// String fieldRef = "pattern:" + "\"" + value + "\""; -// fields.add(fieldRef); -// } + if (stringSchema.getPattern() != null) { + String value = stringSchema.getPattern(); + // This is to check whether the pattern is valid or not. + // TODO: This temp fix will be removed with available with the new Regex API. + // https://github.com/ballerina-platform/ballerina-lang/issues/40328 + // https://github.com/ballerina-platform/ballerina-lang/issues/40318 + try { + Pattern.compile(value, Pattern.UNICODE_CHARACTER_CLASS); + // Ballerina parser + RegExpFactory.parse(value); + String fieldRef = String.format("pattern: re`%s`", value); + fields.add(fieldRef); + } catch (BError err) { + //This handle a case which Ballerina doesn't support + OUT_STREAM.printf("WARNING: skipped generation for unsupported pattern in ballerina: %s %n", value); + } catch (Exception e) { + // This try catch is to check whether the pattern is valid or not. Swagger parser doesn't provide any + // error for invalid patterns. Therefore, we need to check it within code. (ex: syntax errors) + OUT_STREAM.printf("WARNING: skipped generation for non-ECMA flavoured pattern: %s %n", value); + } + } return fields; } - private static List getArrayAnnotFields(ArraySchema arraySchema) { + private static List getArrayAnnotFields(Schema arraySchema) { + List fields = new ArrayList<>(); - if (arraySchema.getMaxItems() != null) { + if (arraySchema.getMaxItems() != null && arraySchema.getMaxItems() != 0) { String value = arraySchema.getMaxItems().toString(); - String fieldRef = MAX_LENGTH + COLON + value; + String fieldRef = GeneratorConstants.MAX_LENGTH + GeneratorConstants.COLON + value; fields.add(fieldRef); } - if (arraySchema.getMinItems() != null) { + if (arraySchema.getMinItems() != null && arraySchema.getMinItems() != 0) { String value = arraySchema.getMinItems().toString(); - String fieldRef = MIN_LENGTH + COLON + value; + String fieldRef = GeneratorConstants.MIN_LENGTH + GeneratorConstants.COLON + value; fields.add(fieldRef); } return fields; @@ -388,6 +487,7 @@ private static List getArrayAnnotFields(ArraySchema arraySchema) { * @return {@link AnnotationNode} */ private static AnnotationNode createAnnotationNode(String annotationReference, String annotFields) { + MappingConstructorExpressionNode annotationBody = null; SimpleNameReferenceNode annotReference = createSimpleNameReferenceNode( createIdentifierToken(annotationReference)); @@ -408,13 +508,14 @@ private static AnnotationNode createAnnotationNode(String annotationReference, S * @return Documentation node list */ public static List getFieldApiDocs(Schema 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 = getValidName(split[split.length - 1], true); + String componentName = GeneratorUtils.getValidName(split[split.length - 1], true); OpenAPI openAPI = GeneratorMetaData.getInstance().getOpenAPI(); if (openAPI.getComponents().getSchemas().get(componentName) != null) { Schema schema = openAPI.getComponents().getSchemas().get(componentName); @@ -436,11 +537,13 @@ public static List getFieldApiDocs(Schema field) { */ public static void getRecordDocs(List documentation, Schema schemaValue, List typeAnnotations) throws BallerinaOpenApiException { + if (schemaValue.getDescription() != null) { documentation.addAll(DocCommentsGenerator.createAPIDescriptionDoc( schemaValue.getDescription(), false)); } else if (schemaValue.get$ref() != null) { - String typeName = getValidName(extractReferenceType(schemaValue.get$ref()), true); + String typeName = GeneratorUtils.getValidName(GeneratorUtils.extractReferenceType( + schemaValue.get$ref()), true); Schema refSchema = GeneratorMetaData.getInstance().getOpenAPI(). getComponents().getSchemas().get(typeName); if (refSchema.getDescription() != null) { @@ -453,40 +556,4 @@ public static void getRecordDocs(List documentation, Schema schemaValue, documentation, typeAnnotations); } } - - /** - * 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 BallerinaOpenApiException when unsupported combination of schemas found - */ - public static TypeDescriptorNode getUnionType(List schemas, String typeName) - throws BallerinaOpenApiException { - List typeDescriptorNodes = new ArrayList<>(); - for (Schema schema : schemas) { - TypeDescriptorNode typeDescriptorNode = getTypeGenerator(schema, typeName, null) - .generateTypeDescriptorNode(); - if (typeDescriptorNode instanceof OptionalTypeDescriptorNode && - GeneratorMetaData.getInstance().isNullable()) { - Node internalTypeDesc = ((OptionalTypeDescriptorNode) typeDescriptorNode).typeDescriptor(); - typeDescriptorNode = (TypeDescriptorNode) internalTypeDesc; - } - typeDescriptorNodes.add(typeDescriptorNode); - } - 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); - } - } } diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java new file mode 100644 index 000000000..ea015d315 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.schema.ballerinatypegenerators; + +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 io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.generators.schema.model.RecordMetadata; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.media.Schema; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +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; +import static io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils.getTypeGenerator; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for allOf schemas. + * -- ex: + * Sample OpenAPI : + *

+ *    schemas:
+ *     Dog:
+ *       allOf:
+ *       - $ref: "#/components/schemas/Pet"
+ *       - type: object
+ *         properties:
+ *           bark:
+ *             type: boolean
+ *  
+ * Generated Ballerina type for the allOf schema `Dog` : + *
+ *  public type Dog record {
+ *      *Pet;
+ *      boolean bark?;
+ *  };
+ * 
+ * + * @since 1.3.0 + */ +public class AllOfRecordTypeGenerator extends RecordTypeGenerator { + private final List> restSchemas = new LinkedList<>(); + + public AllOfRecordTypeGenerator(Schema schema, String typeName) { + super(schema, typeName); + } + + /** + * Generates TypeDescriptorNode for allOf schemas. + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { + // 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. + List allOfSchemas = schema.getAllOf(); + + RecordMetadata recordMetadata = getRecordMetadata(); + RecordRestDescriptorNode restDescriptorNode = recordMetadata.getRestDescriptorNode(); + if (allOfSchemas.size() == 1 && allOfSchemas.get(0).get$ref() != null) { + ReferencedTypeGenerator referencedTypeGenerator = new ReferencedTypeGenerator(allOfSchemas.get(0), + typeName); + return referencedTypeGenerator.generateTypeDescriptorNode(); + } else { + List 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 BallerinaOpenApiException { + + List recordFieldList = new ArrayList<>(); + for (Schema allOfSchema : allOfSchemas) { + 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. + OpenAPI openAPI = GeneratorMetaData.getInstance().getOpenAPI(); + Schema refSchema = openAPI.getComponents().getSchemas().get(modifiedSchemaName); + addAdditionalSchemas(refSchema); + + recordFieldList.add(recordField); + } else if (allOfSchema.getProperties() != null) { + Map> properties = allOfSchema.getProperties(); + List required = allOfSchema.getRequired(); + recordFieldList.addAll(addRecordFields(required, properties.entrySet(), typeName)); + addAdditionalSchemas(allOfSchema); + } else if (GeneratorUtils.isComposedSchema(allOfSchema)) { + if (allOfSchema.getAllOf() != null) { + recordFieldList.addAll(generateAllOfRecordFields(allOfSchema.getAllOf())); + } else { + // TODO: Needs to improve the error message. Could not access the schema name at this level. + throw new BallerinaOpenApiException( + "Unsupported nested OneOf or AnyOf schema is found inside a AllOf schema."); + } + } + } + return recordFieldList; + } + + /** + * 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. + * + * ex: string|int... + * @return + */ + private RecordRestDescriptorNode getRestDescriptorNodeForAllOf(List> restSchemas) + throws BallerinaOpenApiException { + 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 BallerinaOpenApiException when unsupported combination of schemas found + */ + private TypeDescriptorNode getUnionType(List> schemas) throws BallerinaOpenApiException { + + // 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(schema, null, null); + TypeDescriptorNode typeDescriptorNode = typeGenerator.generateTypeDescriptorNode(); + imports.addAll(typeGenerator.getImports()); + typeDescriptorNodes.add(typeDescriptorNode); + // error for rest field unhandled constraint support + if (GeneratorUtils.hasConstraints(schema)) { + // use printStream for echo the error, because current openapi to ballerina implementation won't + // handle diagnostic message. + OUT_STREAM.println("WARNING: constraints in the OpenAPI 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); + } + } + + private void addAdditionalSchemas(Schema refSchema) { + if (refSchema.getAdditionalProperties() != null && refSchema.getAdditionalProperties() instanceof Schema) { + restSchemas.add((Schema) refSchema.getAdditionalProperties()); + } + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java similarity index 77% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java index 525bf60bd..9701a10e6 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java @@ -1,27 +1,27 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; +package io.ballerina.openapi.core.generators.schema.ballerinatypegenerators; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorConstants; -import io.ballerina.openapi.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; import io.swagger.v3.oas.models.media.Schema; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; @@ -40,7 +40,7 @@ * public type Pet anydata; * * - * @since 2.0.0 + * @since 1.3.0 */ public class AnyDataTypeGenerator extends TypeGenerator { diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java similarity index 69% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java index b0093fd49..f19ed8a9c 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; +package io.ballerina.openapi.core.generators.schema.ballerinatypegenerators; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; @@ -29,9 +29,11 @@ import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.TypeGeneratorUtils; -import io.swagger.v3.oas.models.media.ArraySchema; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.swagger.v3.oas.models.media.Schema; import java.util.ArrayList; @@ -43,11 +45,9 @@ import static io.ballerina.compiler.syntax.tree.NodeFactory.createToken; import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; -import static io.ballerina.openapi.generators.GeneratorConstants.MAX_ARRAY_LENGTH; -import static io.ballerina.openapi.generators.GeneratorConstants.SPECIAL_CHARACTER_REGEX; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; -import static io.ballerina.openapi.generators.GeneratorUtils.hasConstraints; -import static io.ballerina.openapi.generators.schema.TypeGeneratorUtils.getNullableType; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIType; +import static io.ballerina.openapi.core.GeneratorUtils.hasConstraints; +import static io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils.getNullableType; /** * Generate TypeDefinitionNode and TypeDescriptorNode for array schemas. @@ -64,19 +64,16 @@ * public type Pets Pet[]; * * - * @since 2.0.0 + * @since 1.3.0 */ public class ArrayTypeGenerator extends TypeGenerator { private String parentType = null; - private TypeDefinitionNode arrayItemWithConstraint = null; + public ArrayTypeGenerator(Schema schema, String typeName, String parentType) { super(schema, typeName); this.parentType = parentType; } - public TypeDefinitionNode getArrayItemWithConstraint() { - return arrayItemWithConstraint; - } /** * Generate TypeDescriptorNode for array type schemas. If array type is not given, type will be `AnyData` @@ -84,40 +81,44 @@ public TypeDefinitionNode getArrayItemWithConstraint() { */ @Override public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - assert schema instanceof ArraySchema; - ArraySchema arraySchema = (ArraySchema) schema; - Schema items = arraySchema.getItems(); - boolean isConstraintsAvailable = hasConstraints(items); + + Schema items = schema.getItems(); + boolean isConstraintsAvailable = + !GeneratorMetaData.getInstance().isNullable() && hasConstraints(items) && typeName != null; TypeGenerator typeGenerator; if (isConstraintsAvailable) { - String normalizedTypeName = typeName.replaceAll(SPECIAL_CHARACTER_REGEX, "").trim(); - typeName = getValidName( - parentType != null ? - parentType + "-" + normalizedTypeName + "-Items-" + items.getType() : - normalizedTypeName + "-Items-" + items.getType(), - true); - typeGenerator = TypeGeneratorUtils.getTypeGenerator(items, typeName, null); + String normalizedTypeName = typeName.replaceAll(GeneratorConstants.SPECIAL_CHARACTER_REGEX, "").trim(); List typeAnnotations = new ArrayList<>(); - AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(items); + AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(typeName, items); if (constraintNode != null) { typeAnnotations.add(constraintNode); } - arrayItemWithConstraint = typeGenerator.generateTypeDefinitionNode( + typeName = GeneratorUtils.getValidName( + parentType != null ? + parentType + "-" + normalizedTypeName + "-Items-" + getOpenAPIType(items) : + normalizedTypeName + "-Items-" + getOpenAPIType(items), + 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; - if (typeGenerator instanceof PrimitiveTypeGenerator && isConstraintsAvailable) { + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); + if ((typeGenerator instanceof PrimitiveTypeGenerator || + typeGenerator instanceof ArrayTypeGenerator) && isConstraintsAvailable) { typeDescriptorNode = NodeParser.parseTypeDescriptor(typeName); } else { typeDescriptorNode = typeGenerator.generateTypeDescriptorNode(); } - if (typeGenerator instanceof UnionTypeGenerator) { + if (typeGenerator instanceof UnionTypeGenerator || (items.getEnum() != null && items.getEnum().size() > 0)) { typeDescriptorNode = createParenthesisedTypeDescriptorNode( createToken(OPEN_PAREN_TOKEN), typeDescriptorNode, createToken(CLOSE_PAREN_TOKEN)); } @@ -126,8 +127,8 @@ public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiEx typeDescriptorNode = (TypeDescriptorNode) node; } - if (arraySchema.getMaxItems() != null) { - if (arraySchema.getMaxItems() > MAX_ARRAY_LENGTH) { + if (schema.getMaxItems() != null) { + if (schema.getMaxItems() > GeneratorConstants.MAX_ARRAY_LENGTH) { throw new BallerinaOpenApiException("Maximum item count defined in the definition exceeds the " + "maximum ballerina array length."); } @@ -145,7 +146,7 @@ public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiEx arrayDimensions = arrayDimensions.add(arrayDimension); ArrayTypeDescriptorNode arrayTypeDescriptorNode = createArrayTypeDescriptorNode(typeDescriptorNode , arrayDimensions); - - return getNullableType(arraySchema, arrayTypeDescriptorNode); + imports.addAll(typeGenerator.getImports()); + return getNullableType(schema, arrayTypeDescriptorNode); } } diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/EnumGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/EnumGenerator.java new file mode 100644 index 000000000..856cd4a63 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/EnumGenerator.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.schema.ballerinatypegenerators; + +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.swagger.v3.oas.models.media.Schema; + +import java.util.List; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.openapi.core.GeneratorConstants.NILLABLE; +import static io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils.PRIMITIVE_TYPE_LIST; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for schemas with enums. + * -- ex: + * Sample OpenAPI : + *
+ *    components:
+ *     schemas:
+ *       MeetingType:
+ *         type: string
+ *         default: live
+ *         enum:
+ *         - "scheduled"
+ *         - "live"
+ *         - "upcoming"
+ *  
+ * Generated Ballerina type for the schema `MeetingTypes` : + *
+ *     public type MeetingTypes "scheduled"|"live"|"upcoming";
+ * 
+ * + * @since 1.6.0 + */ +public class EnumGenerator extends TypeGenerator { + + public EnumGenerator(Schema schema, String typeName) { + super(schema, typeName); + } + + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { + List enumList = schema.getEnum(); + boolean isNull = false; + StringBuilder enumBuilder = new StringBuilder(); + if (PRIMITIVE_TYPE_LIST.contains(GeneratorUtils.getOpenAPIType(schema))) { + for (Object enumValue : enumList) { + isNull = enumValue == null; + if (isNull) { + continue; + } + if (enumValue instanceof String) { + enumBuilder.append("\"").append(enumValue).append("\"").append("|"); + } else { + enumBuilder.append(enumValue).append("|"); + } + } + if (enumBuilder.length() > 0) { + enumBuilder.deleteCharAt(enumBuilder.length() - 1); + String enumString = isNull ? enumBuilder.toString() + NILLABLE : enumBuilder.toString(); + return NodeParser.parseTypeDescriptor(enumString); + } else { + String typeDescriptorName; + if (GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.containsKey(schema.getType().trim())) { + typeDescriptorName = GeneratorConstants.OPENAPI_TYPE_TO_BAL_TYPE_MAP.get( + GeneratorUtils.getOpenAPIType(schema)); + } else { + throw new BallerinaOpenApiException("Unsupported OAS data type `" + schema.getType().trim() + "`"); + } + if (isNull) { + return createSimpleNameReferenceNode(createIdentifierToken(typeDescriptorName + NILLABLE)); + } else { + TypeDescriptorNode typeDescriptorNode = createSimpleNameReferenceNode( + createIdentifierToken(typeDescriptorName)); + return TypeGeneratorUtils.getNullableType(schema, typeDescriptorNode); + } + } + } else { + throw new BallerinaOpenApiException(String.format("The data type '%s' is not a valid enum type." + + "The supported types are string, integer, number and boolean", + GeneratorUtils.getOpenAPIType(schema))); + } + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java similarity index 59% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java index c26779aea..2f4ee9c09 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java @@ -1,32 +1,32 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; +package io.ballerina.openapi.core.generators.schema.ballerinatypegenerators; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; import io.swagger.v3.oas.models.media.Schema; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorConstants.NUMBER; -import static io.ballerina.openapi.generators.GeneratorUtils.convertOpenAPITypeToBallerina; /** * Generate TypeDefinitionNode and TypeDescriptorNode for primitive type schemas. @@ -43,7 +43,7 @@ * public type PetName string; * * - * @since 2.0.0 + * @since 1.3.0 */ public class PrimitiveTypeGenerator extends TypeGenerator { @@ -57,12 +57,17 @@ public PrimitiveTypeGenerator(Schema schema, String typeName) { */ @Override public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - String typeDescriptorName = convertOpenAPITypeToBallerina(schema.getType().trim()); + String typeDescriptorName = GeneratorUtils.convertOpenAPITypeToBallerina(schema); // TODO: Need to the format of other primitive types too - if (schema.getType().equals(NUMBER)) { - if (schema.getFormat() != null) { - typeDescriptorName = convertOpenAPITypeToBallerina(schema.getFormat().trim()); - } + if (schema.getEnum() != null && schema.getEnum().size() > 0) { + EnumGenerator enumGenerator = new EnumGenerator(schema, typeName); + typeDescriptorName = enumGenerator.generateTypeDescriptorNode().toString(); + return createSimpleNameReferenceNode( + createIdentifierToken(typeDescriptorName)); + } else if (GeneratorUtils.getOpenAPIType(schema).equals(GeneratorConstants.STRING) && + schema.getFormat() != null && + schema.getFormat().equals(GeneratorConstants.BINARY)) { + typeDescriptorName = "record {byte[] fileContent; string fileName;}"; } TypeDescriptorNode typeDescriptorNode = createSimpleNameReferenceNode( createIdentifierToken(typeDescriptorName)); diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java new file mode 100644 index 000000000..87bfea050 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.schema.ballerinatypegenerators; + +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.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.generators.schema.model.RecordMetadata; +import io.swagger.v3.oas.models.media.Schema; +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.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. + * -- ex: + * Sample OpenAPI : + *
+ *      components:
+ *          schemas:
+ *              Pet:
+ *                  required:
+ *                      - id
+ *                      - name
+ *                  properties:
+ *                      id:
+ *                          type: integer
+ *                          format: int64
+ *                      name:
+ *                          type: string
+ *                      tag:
+ *                          type: string
+ *                      type:
+ *                          type: string
+ *  
+ * Generated Ballerina type for the schema `Pet` : + *
+ * public type Pet record {
+ *      int id;
+ *      string name;
+ *      string tag?;
+ *      string 'type?;
+ * };
+ * 
+ * + * @since 1.3.0 + */ +public class RecordTypeGenerator extends TypeGenerator { + + public static final PrintStream OUT_STREAM = System.err; + public RecordTypeGenerator(Schema schema, String typeName) { + super(schema, typeName); + } + + /** + * Generate TypeDescriptorNode for object type schemas. + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { + + List recordFields = new LinkedList<>(); + // extract metadata with additional properties + RecordMetadata metadataBuilder = getRecordMetadata(); + + if (schema.getProperties() != null) { + Map> properties = schema.getProperties(); + List required = schema.getRequired(); + recordFields.addAll(addRecordFields(required, properties.entrySet(), typeName)); + NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFields); + return 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)); + } else { + return 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)); + } + } + + /** + * 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 BallerinaOpenApiException throws when process has some failure. + */ + public RecordMetadata getRecordMetadata() throws BallerinaOpenApiException { + boolean isOpenRecord = true; + RecordRestDescriptorNode recordRestDescNode = null; + + if (schema.getAdditionalProperties() != null) { + Object additionalProperties = schema.getAdditionalProperties(); + if (additionalProperties instanceof Schema) { + Schema additionalPropSchema = (Schema) additionalProperties; + if (GeneratorUtils.hasConstraints(additionalPropSchema)) { + // use printStream to echo the error, because current openapi to ballerina implementation doesn't + // handle diagnostic message. + isOpenRecord = false; + OUT_STREAM.println("WARNING: constraints in the OpenAPI 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 (GeneratorUtils.getOpenAPIType(additionalPropSchema) != null) { + isOpenRecord = false; + recordRestDescNode = getRecordRestDescriptorNode(additionalPropSchema); + } else if (GeneratorUtils.isComposedSchema(additionalPropSchema)) { + OUT_STREAM.println("WARNING: generating Ballerina rest record field will be ignored for the " + + "OpenAPI contract additionalProperties type `ComposedSchema`, as it is not supported on " + + "Ballerina rest record field."); + } + } else if (additionalProperties.equals(false)) { + isOpenRecord = false; + } + } + + return new RecordMetadata.Builder() + .withIsOpenRecord(isOpenRecord) + .withRestDescriptorNode(recordRestDescNode).build(); + } + + /** + * Creates reference rest node when additional property has reference. + */ + public RecordRestDescriptorNode getRestDescriptorNodeForReference(Schema additionalPropSchema) + throws BallerinaOpenApiException { + 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. + *
+     *    type User record {
+     *       string...;
+     *     }
+     * 
+ */ + public static RecordRestDescriptorNode getRecordRestDescriptorNode(Schema additionalPropSchema) + throws BallerinaOpenApiException { + + RecordRestDescriptorNode recordRestDescNode = null; + if (GeneratorUtils.isNumberSchema(additionalPropSchema) && additionalPropSchema.getFormat() != null) { + // this is special for `NumberSchema` because it has format with its expected type. + SimpleNameReferenceNode numberNode = NodeFactory.createSimpleNameReferenceNode( + createIdentifierToken(GeneratorUtils.convertOpenAPITypeToBallerina(additionalPropSchema))); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode( + TypeGeneratorUtils.getNullableType(additionalPropSchema, numberNode), + createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else if (GeneratorUtils.isObjectSchema(additionalPropSchema) || + GeneratorUtils.isMapSchema(additionalPropSchema)) { + 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 (GeneratorUtils.isArraySchema(additionalPropSchema)) { + ArrayTypeGenerator arrayTypeGenerator = new ArrayTypeGenerator(additionalPropSchema, null, null); + TypeDescriptorNode arrayNode = arrayTypeGenerator.generateTypeDescriptorNode(); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode(arrayNode, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else if (GeneratorUtils.isIntegerSchema(additionalPropSchema) || + GeneratorUtils.isStringSchema(additionalPropSchema) || + GeneratorUtils.isBooleanSchema(additionalPropSchema)) { + 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`", + GeneratorUtils.getOpenAPIType(additionalPropSchema)); + } + return recordRestDescNode; + } + + /** + * This util for generating record field with given schema properties. + */ + public List addRecordFields(List required, Set>> fields, + String recordName) throws BallerinaOpenApiException { + // TODO: Handle allOf , oneOf, anyOf + List recordFieldList = new ArrayList<>(); + for (Map.Entry> field : fields) { + String fieldNameStr = GeneratorUtils.escapeIdentifier(field.getKey().trim()); + // API doc generations + Schema fieldSchema = 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); + } + 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/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java similarity index 70% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java index 64555a223..96462ff0d 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java @@ -1,39 +1,38 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; +package io.ballerina.openapi.core.generators.schema.ballerinatypegenerators; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.schema.TypeGeneratorUtils; -import io.ballerina.openapi.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.swagger.v3.oas.models.media.Schema; import static io.ballerina.compiler.syntax.tree.NodeFactory.createIdentifierToken; import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType; -import static io.ballerina.openapi.generators.GeneratorUtils.getValidName; /** * Generate TypeDefinitionNode and TypeDescriptorNode for referenced schemas. * -- ex: * Sample OpenAPI : - *
+ * 
  *      components:
  *          schemas:
  *              PetName:
@@ -46,7 +45,7 @@
  *     public type DogName PetName;
  * 
* - * @since 2.0.0 + * @since 1.3.0 */ public class ReferencedTypeGenerator extends TypeGenerator { @@ -59,8 +58,12 @@ public ReferencedTypeGenerator(Schema schema, String typeName) { */ @Override public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { - String typeName = getValidName(extractReferenceType(schema.get$ref()), true); + + String extractName = GeneratorUtils.extractReferenceType(schema.get$ref()); + String typeName = GeneratorUtils.getValidName(extractName, true); Schema refSchema = GeneratorMetaData.getInstance().getOpenAPI().getComponents().getSchemas().get(typeName); + refSchema = refSchema == null ? + GeneratorMetaData.getInstance().getOpenAPI().getComponents().getSchemas().get(extractName) : refSchema; TypeDescriptorNode typeDescriptorNode = createSimpleNameReferenceNode(createIdentifierToken(typeName)); if (refSchema == null) { throw new BallerinaOpenApiException(String.format("Undefined $ref: '%s' in openAPI contract.", diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/TypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/TypeGenerator.java similarity index 65% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/TypeGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/TypeGenerator.java index 9464c6e3e..4cd209529 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/ballerinatypegenerators/TypeGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/TypeGenerator.java @@ -1,33 +1,38 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.schema.ballerinatypegenerators; +package io.ballerina.openapi.core.generators.schema.ballerinatypegenerators; 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 io.ballerina.openapi.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; import io.swagger.v3.oas.models.media.Schema; +import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; @@ -38,18 +43,34 @@ 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; +import static io.ballerina.openapi.core.GeneratorConstants.BALLERINA; +import static io.ballerina.openapi.core.GeneratorConstants.CONSTRAINT; /** * Abstract class for schema types. + * + * @since 1.3.0 */ public abstract class TypeGenerator { + Schema schema; String typeName; + final List typeDefinitionNodeList = new ArrayList<>(); + final LinkedHashSet imports = new LinkedHashSet<>(); + public TypeGenerator(Schema 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 OpenAPI schema. * @@ -62,6 +83,18 @@ public TypeGenerator(Schema schema, String typeName) { public TypeDefinitionNode generateTypeDefinitionNode(IdentifierToken typeName, List schemaDoc, List typeAnnotations) throws BallerinaOpenApiException { + + //Check the annotation for constraint support + boolean nullable = GeneratorMetaData.getInstance().isNullable(); + for (AnnotationNode annotation : typeAnnotations) { + String annotationRef = annotation.annotReference().toString(); + if (annotationRef.startsWith(CONSTRAINT) && !nullable) { + 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), diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java new file mode 100644 index 000000000..ef37ebb6e --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.schema.ballerinatypegenerators; + +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 io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; +import io.swagger.v3.oas.models.media.Schema; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +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; +import static io.ballerina.openapi.core.generators.schema.TypeGeneratorUtils.getTypeGenerator; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for anyOf and oneOf schemas. + * -- ex: + * Sample OpenAPI : + *
+ *    schemas:
+ *     Employee:
+ *       anyOf:
+ *       - $ref: "#/components/schemas/InternalEmployee"
+ *       - $ref: "#/components/schemas/ExternalEmployee"
+ *  
+ * Generated Ballerina type for the anyOf schema `Employee` : + *
+ *  public type Employee InternalEmployee|ExternalEmployee
+ * 
+ * + * @since 1.3.0 + */ +public class UnionTypeGenerator extends TypeGenerator { + + public UnionTypeGenerator(Schema schema, String typeName) { + super(schema, typeName); + } + + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaOpenApiException { + + List schemas; + if (schema.getOneOf() != null) { + schemas = schema.getOneOf(); + } else { + schemas = schema.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 BallerinaOpenApiException when unsupported combination of schemas found + */ + private TypeDescriptorNode getUnionType(List schemas, String typeName) + throws BallerinaOpenApiException { + + List typeDescriptorNodes = new ArrayList<>(); + for (Schema schema : schemas) { + TypeGenerator typeGenerator = getTypeGenerator(schema, typeName, null); + TypeDescriptorNode typeDescNode = typeGenerator.generateTypeDescriptorNode(); + imports.addAll(typeGenerator.getImports()); + if (typeDescNode instanceof OptionalTypeDescriptorNode && GeneratorMetaData.getInstance().isNullable()) { + 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/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/GeneratorMetaData.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/GeneratorMetaData.java new file mode 100644 index 000000000..de506807d --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/GeneratorMetaData.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.schema.model; + +import io.swagger.v3.oas.models.OpenAPI; + +/** + * Stores metadata related to Ballerina types generation. + * + * @since 1.3.0 + */ +public class GeneratorMetaData { + + private final OpenAPI openAPI; + private final boolean nullable; + private final boolean generateServiceType; + private static GeneratorMetaData generatorMetaData = null; + + private GeneratorMetaData(OpenAPI openAPI, boolean nullable, boolean generateServiceType) { + this.openAPI = openAPI; + this.nullable = nullable; + this.generateServiceType = generateServiceType; + } + + public static void createInstance(OpenAPI openAPI, boolean nullable, boolean generateServiceType) { + generatorMetaData = new GeneratorMetaData(openAPI, nullable, generateServiceType); + } + + public static GeneratorMetaData getInstance() { + return generatorMetaData; + } + + public OpenAPI getOpenAPI() { + return openAPI; + } + + public boolean isNullable() { + return nullable; + } + + public boolean isServiceTypeRequired() { + return generateServiceType; + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/RecordMetadata.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/RecordMetadata.java new file mode 100644 index 000000000..a22626585 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/schema/model/RecordMetadata.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.openapi.core.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. + * + * @since 1.4.0 + */ +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; + } + + /** + * Record meta data builder class for {@code RecordMetadata}. + * + * @since 1.4.0 + */ + 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/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceGenerator.java new file mode 100644 index 000000000..3de6ec406 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceGenerator.java @@ -0,0 +1,446 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyBlockNode; +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.ListenerDeclarationNode; +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.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.ServiceDeclarationNode; +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.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.ballerina.openapi.core.generators.schema.model.GeneratorMetaData; +import io.ballerina.openapi.core.generators.service.model.OASServiceMetadata; +import io.ballerina.openapi.core.model.Filter; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.Paths; +import io.swagger.v3.oas.models.parameters.RequestBody; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +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.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.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.createRequiredParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createServiceDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.openapi.core.GeneratorConstants.CALLER; +import static io.ballerina.openapi.core.GeneratorConstants.CATCH_ALL_PATH; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_FUNC_COMMENT; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_PARAM_COMMENT; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_CALLER; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.SERVICE_TYPE_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.SLASH; +import static io.ballerina.openapi.core.GeneratorUtils.escapeIdentifier; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.createImportDeclarationNodes; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.generateServiceConfigAnnotation; + +/** + * This Util class use for generating ballerina service file according to given yaml file. + * + * @since 1.3.0 + */ +public class BallerinaServiceGenerator { + + private boolean isNullableRequired; + private final OpenAPI openAPI; + private final Filter filter; + private final boolean isServiceTypeRequired; + private final boolean generateWithoutDataBinding; + private final BallerinaTypesGenerator ballerinaSchemaGenerator; + private List functionList = new ArrayList<>(); + private final Map typeInclusionRecords = new HashMap<>(); + private final Set paths = new LinkedHashSet<>(); + + public BallerinaServiceGenerator(OASServiceMetadata oasServiceMetadata) { + this.openAPI = oasServiceMetadata.getOpenAPI(); + this.filter = oasServiceMetadata.getFilters(); + this.isNullableRequired = false; + this.isServiceTypeRequired = oasServiceMetadata.isServiceTypeRequired(); + this.generateWithoutDataBinding = oasServiceMetadata.generateWithoutDataBinding(); + this.ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPI, oasServiceMetadata.isNullable(), + new LinkedList<>()); + GeneratorMetaData.createInstance(openAPI, oasServiceMetadata.isNullable(), + oasServiceMetadata.isServiceTypeRequired()); + } + + public List getFunctionList() { + return functionList; + } + + public void setFunctionList(List functionList) { + this.functionList = functionList; + } + + public List getTypeInclusionRecords() { + List typeRecords = new ArrayList<>(); + this.typeInclusionRecords.forEach((key, value) -> { + typeRecords.add(value); + }); + return typeRecords; + } + + public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException { + // Create imports http and openapi + NodeList imports = createImportDeclarationNodes(); + // Need to Generate Base path + ListenerGenerator listener = new ListenerGenerator(); + ListenerDeclarationNode listenerDeclarationNode = listener.getListenerDeclarationNodes(openAPI.getServers()); + NodeList absoluteResourcePath = createBasePathNodeList(listener); + + SimpleNameReferenceNode listenerName = createSimpleNameReferenceNode(listenerDeclarationNode.variableName()); + SeparatedNodeList expressions = createSeparatedNodeList(listenerName); + + // Fill the members with function + List functions = createResourceFunctions(openAPI, filter); + this.setFunctionList(functions); + + NodeList members = createNodeList(functions); + // Create annotation if nullable property is enabled + // @http:ServiceConfig { + // treatNilableAsOptional : false + //} + MetadataNode metadataNode = null; + if (isNullableRequired) { + metadataNode = generateServiceConfigAnnotation(); + } + TypeDescriptorNode serviceType = null; + if (isServiceTypeRequired) { + serviceType = createSimpleNameReferenceNode(createIdentifierToken(SERVICE_TYPE_NAME)); + } + ServiceDeclarationNode serviceDeclarationNode = createServiceDeclarationNode( + metadataNode, createEmptyNodeList(), createToken(SyntaxKind.SERVICE_KEYWORD, + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE), + serviceType, absoluteResourcePath, createToken(SyntaxKind.ON_KEYWORD, + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE), expressions, + createToken(SyntaxKind.OPEN_BRACE_TOKEN), members, createToken(SyntaxKind.CLOSE_BRACE_TOKEN), null); + + // Create module member declaration + NodeList moduleMembers = createNodeList( + listenerDeclarationNode, serviceDeclarationNode); + + Token eofToken = createIdentifierToken(""); + ModulePartNode modulePartNode = createModulePartNode(imports, moduleMembers, eofToken); + + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + return syntaxTree.modifyWith(modulePartNode); + } + + private List createResourceFunctions(OpenAPI openApi, Filter filter) throws BallerinaOpenApiException { + + List functions = new ArrayList<>(); + if (!openApi.getPaths().isEmpty()) { + Paths paths = openApi.getPaths(); + Set> pathsItems = paths.entrySet(); + for (Map.Entry path : pathsItems) { + if (!path.getValue().readOperationsMap().isEmpty()) { + Map operationMap = path.getValue().readOperationsMap(); + functions.addAll(applyFiltersForOperations(filter, path.getKey(), operationMap)); + } + } + } + return functions; + } + + private NodeList createBasePathNodeList(ListenerGenerator listener) { + + if (GeneratorConstants.OAS_PATH_SEPARATOR.equals(listener.getBasePath())) { + return createNodeList(createIdentifierToken(listener.getBasePath())); + } else { + String[] basePathNode = listener.getBasePath().split(GeneratorConstants.OAS_PATH_SEPARATOR); + List basePath = Arrays.stream(basePathNode).filter(node -> !node.isBlank()) + .map(node -> createIdentifierToken(GeneratorConstants.OAS_PATH_SEPARATOR + + GeneratorUtils.escapeIdentifier(node))).collect(Collectors.toList()); + return createNodeList(basePath); + } + } + + private List applyFiltersForOperations(Filter filter, String path, + Map operationMap) + throws BallerinaOpenApiException { + + List functions = new ArrayList<>(); + for (Map.Entry operation : operationMap.entrySet()) { + List resourceFunctionDocs = new ArrayList<>(); + addFunctionDescToAPIDocs(operation, resourceFunctionDocs); + //Add filter availability + //1.Tag filter + //2.Operation filter + //3. Both tag and operation filter + List filterTags = filter.getTags(); + List operationTags = operation.getValue().getTags(); + List filterOperations = filter.getOperations(); + if (!filterTags.isEmpty() || !filterOperations.isEmpty()) { + if (operationTags != null || ((!filterOperations.isEmpty()) + && (operation.getValue().getOperationId() != null))) { + if ((operationTags != null && GeneratorUtils.hasTags(operationTags, filterTags)) || + ((operation.getValue().getOperationId() != null) && + filterOperations.contains(operation.getValue().getOperationId().trim()))) { + // getRelative resource path + List functionRelativeResourcePath = GeneratorUtils.getRelativeResourcePath(path, + operation.getValue(), resourceFunctionDocs); + // function call + + FunctionDefinitionNode functionDefinitionNode = generateWithoutDataBinding ? + generateGenericResourceFunctions(operation, + functionRelativeResourcePath, path, resourceFunctionDocs) : + getResourceFunction(operation, functionRelativeResourcePath, path, + resourceFunctionDocs); + functions.add(functionDefinitionNode); + } + } + } else { + // getRelative resource path + List relativeResourcePath = GeneratorUtils.getRelativeResourcePath(path, operation.getValue(), + resourceFunctionDocs); + // function call + FunctionDefinitionNode resourceFunction = generateWithoutDataBinding ? + generateGenericResourceFunctions(operation, + relativeResourcePath, path, resourceFunctionDocs) : getResourceFunction(operation, + relativeResourcePath, path, resourceFunctionDocs); + functions.add(resourceFunction); + } + } + return functions; + } + + private FunctionDefinitionNode generateGenericResourceFunctions(Map.Entry operation, + List pathNodes, String path, + List resourceFunctionDocs) { + NodeList qualifiersList = createNodeList(createIdentifierToken(GeneratorConstants.RESOURCE, + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE)); + Token functionKeyWord = createIdentifierToken(GeneratorConstants.FUNCTION, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + IdentifierToken functionName = createIdentifierToken(operation.getKey().name() + .toLowerCase(Locale.ENGLISH), GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE); + NodeList relativeResourcePath = createNodeList(pathNodes); + List parameters = new ArrayList<>(); + // create parameter `http:Caller caller` + BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(HTTP_CALLER)); + IdentifierToken paramName = createIdentifierToken(CALLER); + RequiredParameterNode httpCaller = createRequiredParameterNode(createEmptyNodeList(), typeName, paramName); + parameters.add(httpCaller); + // create parameter `http:Request request` + parameters.add(createToken(COMMA_TOKEN)); + BuiltinSimpleNameReferenceNode typeNameRequest = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(HTTP_REQUEST)); + IdentifierToken paramNameRequest = createIdentifierToken(REQUEST); + RequiredParameterNode httpRequest = createRequiredParameterNode(createEmptyNodeList(), typeNameRequest, + paramNameRequest); + parameters.add(httpRequest); + + SeparatedNodeList parameterList = createSeparatedNodeList(parameters); + + ReturnTypeDescriptorNode returnTypeDescriptorNode = + createReturnTypeDescriptorNode(createToken(SyntaxKind.RETURNS_KEYWORD), createEmptyNodeList(), + createSimpleNameReferenceNode(createIdentifierToken("error?"))); + + // create function signature + FunctionSignatureNode functionSignatureNode = createFunctionSignatureNode(createToken( + SyntaxKind.OPEN_PAREN_TOKEN), parameterList, createToken(SyntaxKind.CLOSE_PAREN_TOKEN), + returnTypeDescriptorNode); + // create function body + FunctionBodyBlockNode functionBodyBlockNode = createFunctionBodyBlockNode( + createToken(SyntaxKind.OPEN_BRACE_TOKEN), + null, createEmptyNodeList(), + createToken(SyntaxKind.CLOSE_BRACE_TOKEN), null); + + return createFunctionDefinitionNode(SyntaxKind.RESOURCE_ACCESSOR_DEFINITION, null, + qualifiersList, functionKeyWord, functionName, relativeResourcePath, functionSignatureNode, + functionBodyBlockNode); + + } + + /** + * Generate resource function for given operation. + * + * @param operation - OAS operation + * @param pathNodes - Relative path nodes + * @return - {@link FunctionDefinitionNode} relevant resource + * @throws BallerinaOpenApiException when the process failure occur + */ + private FunctionDefinitionNode getResourceFunction(Map.Entry operation, + List pathNodes, String path, + List resourceFunctionDocs) + throws BallerinaOpenApiException { + + NodeList qualifiersList = createNodeList(createIdentifierToken(GeneratorConstants.RESOURCE, + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE)); + Token functionKeyWord = createIdentifierToken(GeneratorConstants.FUNCTION, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + IdentifierToken functionName = createIdentifierToken(operation.getKey().name() + .toLowerCase(Locale.ENGLISH), GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE); + NodeList relativeResourcePath = createNodeList(pathNodes); + ParametersGenerator parametersGenerator = new ParametersGenerator(false, openAPI); + parametersGenerator.generateResourcesInputs(operation, resourceFunctionDocs); + List params = new ArrayList<>(parametersGenerator.getRequiredParams()); + + // Handle request Body (Payload) + if (operation.getValue().getRequestBody() != null) { + RequestBody requestBody = operation.getValue().getRequestBody(); + requestBody = resolveRequestBodyReference(requestBody); + RequiredParameterNode nodeForRequestBody = null; + if (requestBody.getContent() != null) { + RequestBodyGenerator requestBodyGen = new RequestBodyGenerator(requestBody); + nodeForRequestBody = requestBodyGen.createNodeForRequestBody(); + params.add(nodeForRequestBody); + params.add(createToken(SyntaxKind.COMMA_TOKEN)); + } + + if (nodeForRequestBody != null && nodeForRequestBody.paramName().isPresent()) { + String description = requestBody.getDescription() != null && !requestBody.getDescription().isBlank() + ? requestBody.getDescription() : DEFAULT_PARAM_COMMENT; + MarkdownParameterDocumentationLineNode paramAPIDoc = + DocCommentsGenerator.createAPIParamDoc(escapeIdentifier( + nodeForRequestBody.paramName().get().text()), + description.split("\n")[0]); + resourceFunctionDocs.add(paramAPIDoc); + } + } + + // For creating the order of the parameters in the function + if (!parametersGenerator.getDefaultableParams().isEmpty()) { + params.addAll(parametersGenerator.getDefaultableParams()); + } + if (params.size() > 1) { + params.remove(params.size() - 1); + } + + if (!isNullableRequired) { + isNullableRequired = parametersGenerator.isNullableRequired(); + } + SeparatedNodeList parameters = createSeparatedNodeList(params); + String pathForRecord = Objects.equals(path, SLASH) || Objects.equals(path, CATCH_ALL_PATH) ? "" : + GeneratorUtils.getValidName(path, true); + ReturnTypeGenerator returnTypeGenerator = new ReturnTypeGenerator(ballerinaSchemaGenerator, pathForRecord, + openAPI); + if (!paths.contains(path)) { + returnTypeGenerator.setCountForRecord(0); + paths.add(path); + } + ReturnTypeDescriptorNode returnNode = returnTypeGenerator.getReturnTypeDescriptorNode(operation, + createEmptyNodeList(), path, resourceFunctionDocs); + typeInclusionRecords.putAll(returnTypeGenerator.getTypeInclusionRecords()); + + FunctionSignatureNode functionSignatureNode = createFunctionSignatureNode( + createToken(SyntaxKind.OPEN_PAREN_TOKEN), + parameters, createToken(SyntaxKind.CLOSE_PAREN_TOKEN), returnNode); + + // Function Body Node + // If path parameter has some special characters, extra body statements are added to handle the complexity. + List bodyStatements = GeneratorUtils.generateBodyStatementForComplexUrl(path); + FunctionBodyBlockNode functionBodyBlockNode = createFunctionBodyBlockNode( + createToken(SyntaxKind.OPEN_BRACE_TOKEN), + null, + bodyStatements.isEmpty() ? + createEmptyNodeList() : + createNodeList(bodyStatements), + createToken(SyntaxKind.CLOSE_BRACE_TOKEN), null); + + List annotationNodes = new ArrayList<>(); + MetadataNode metadataNode = createMetadataNode(createMarkdownDocumentationNode( + createNodeList(resourceFunctionDocs)), createNodeList(annotationNodes)); + + return createFunctionDefinitionNode(SyntaxKind.RESOURCE_ACCESSOR_DEFINITION, metadataNode, + qualifiersList, functionKeyWord, functionName, relativeResourcePath, functionSignatureNode, + functionBodyBlockNode); + } + + private static void addFunctionDescToAPIDocs(Map.Entry operation, + List resourceFunctionDocs) { + // Add function description + if (operation.getValue().getSummary() != null) { + resourceFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + operation.getValue().getSummary(), true)); + } else if (operation.getValue().getDescription() != null && !operation.getValue().getDescription().isBlank()) { + resourceFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + operation.getValue().getDescription(), true)); + } else { + resourceFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + DEFAULT_FUNC_COMMENT, true)); + } + } + + /** + * Resolve requestBody reference. + */ + private RequestBody resolveRequestBodyReference(RequestBody requestBody) throws BallerinaOpenApiException { + + if (requestBody.get$ref() != null) { + String requestBodyName = GeneratorUtils.extractReferenceType(requestBody.get$ref()); + requestBody = resolveRequestBodyReference(openAPI.getComponents() + .getRequestBodies().get(requestBodyName.trim())); + } + return requestBody; + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceObjectGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceObjectGenerator.java new file mode 100644 index 000000000..b9d01fa51 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/BallerinaServiceObjectGenerator.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.MethodDeclarationNode; +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.ObjectTypeDescriptorNode; +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.TypeReferenceNode; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +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.createMethodDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createModulePartNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createObjectTypeDescriptorNode; +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.SyntaxKind.ASTERISK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RESOURCE_ACCESSOR_DECLARATION; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RESOURCE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SERVICE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD; +import static io.ballerina.openapi.core.GeneratorConstants.SERVICE_TYPE_NAME; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.createImportDeclarationNodes; + +/** + * This class is used to generate the ballerina service object for the given openapi contract. + */ +public class BallerinaServiceObjectGenerator { + private final List resourceFunctionList; + + public BallerinaServiceObjectGenerator(List resourceFunctionList) { + this.resourceFunctionList = resourceFunctionList; + } + + public SyntaxTree generateSyntaxTree() { + // TODO: Check the possibility of having imports other than `ballerina/http` + NodeList imports = createImportDeclarationNodes(); + NodeList moduleMembers = createNodeList(generateServiceObject()); + Token eofToken = createIdentifierToken(""); + ModulePartNode modulePartNode = createModulePartNode(imports, moduleMembers, eofToken); + + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + return syntaxTree.modifyWith(modulePartNode); + } + + public TypeDefinitionNode generateServiceObject() { + List serviceObjectMemberNodes = new ArrayList<>(); + TypeReferenceNode httpServiceTypeRefNode = createTypeReferenceNode(createToken(ASTERISK_TOKEN), + createIdentifierToken("http:Service"), createToken(SEMICOLON_TOKEN)); + serviceObjectMemberNodes.add(httpServiceTypeRefNode); + for (Node functionNode : resourceFunctionList) { + NodeList methodQualifierList = createNodeList(createToken(RESOURCE_KEYWORD)); + if (functionNode instanceof FunctionDefinitionNode && + ((FunctionDefinitionNode) functionNode).qualifierList() + .stream().anyMatch(token -> Objects.equals(token.text(), RESOURCE_KEYWORD.stringValue()))) { + FunctionDefinitionNode resourceFunctionDefinitionNode = (FunctionDefinitionNode) functionNode; + MethodDeclarationNode resourceMethodDeclarationNode = createMethodDeclarationNode( + RESOURCE_ACCESSOR_DECLARATION, null, + methodQualifierList, + createToken(FUNCTION_KEYWORD), + resourceFunctionDefinitionNode.functionName(), + resourceFunctionDefinitionNode.relativeResourcePath(), + resourceFunctionDefinitionNode.functionSignature(), + createToken(SEMICOLON_TOKEN)); + serviceObjectMemberNodes.add(resourceMethodDeclarationNode); + } + } + + NodeList members = createNodeList(serviceObjectMemberNodes); + NodeList objectQualifierList = createNodeList(createToken(SERVICE_KEYWORD)); + ObjectTypeDescriptorNode objectTypeDescriptorNode = createObjectTypeDescriptorNode( + objectQualifierList, + createToken(SyntaxKind.OBJECT_KEYWORD), + createToken(SyntaxKind.OPEN_BRACE_TOKEN), + members, + createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); + + return createTypeDefinitionNode(null, null, createToken(TYPE_KEYWORD), + createIdentifierToken(SERVICE_TYPE_NAME), objectTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ListenerGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ListenerGenerator.java similarity index 81% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ListenerGenerator.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ListenerGenerator.java index 95f5207cd..675f419cc 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ListenerGenerator.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ListenerGenerator.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package io.ballerina.openapi.generators.service; +package io.ballerina.openapi.core.generators.service; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.BasicLiteralNode; @@ -35,8 +35,9 @@ import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.openapi.exception.BallerinaOpenApiException; -import io.ballerina.openapi.generators.GeneratorUtils; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.servers.ServerVariables; @@ -44,15 +45,10 @@ import java.net.URL; import java.util.List; -import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG; -import static io.ballerina.openapi.generators.GeneratorConstants.HOST; -import static io.ballerina.openapi.generators.GeneratorConstants.NEW; -import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE; - /** * This util class for processing the mapping in between openAPI server section with ballerina listeners. * - * @since 2.0.0 + * @since 1.3.0 */ public class ListenerGenerator { private static final int HTTP_PORT = 80; @@ -69,8 +65,8 @@ public String getBasePath() { /** * Generate listener accoring to the given server details. * - * @param servers OAS server details - * @return {@link ListenerDeclarationNode} for server. + * @param servers OAS server details + * @return {@link ListenerDeclarationNode} for server. * @throws BallerinaOpenApiException when process break with exception */ public ListenerDeclarationNode getListenerDeclarationNodes(List servers) throws BallerinaOpenApiException { @@ -106,33 +102,33 @@ public ListenerDeclarationNode getListenerDeclarationNodes(List servers) public static ListenerDeclarationNode getListenerDeclarationNode(Integer port, String host, String ep) { // Take first server to Map - Token listenerKeyword = AbstractNodeFactory.createIdentifierToken("listener", SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE); + Token listenerKeyword = AbstractNodeFactory.createIdentifierToken("listener", GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); // Create type descriptor - Token modulePrefix = AbstractNodeFactory.createIdentifierToken("http", SINGLE_WS_MINUTIAE, - SINGLE_WS_MINUTIAE); - IdentifierToken identifier = AbstractNodeFactory.createIdentifierToken("Listener", SINGLE_WS_MINUTIAE, - AbstractNodeFactory.createEmptyMinutiaeList()); + Token modulePrefix = AbstractNodeFactory.createIdentifierToken("http", GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + IdentifierToken identifier = AbstractNodeFactory.createIdentifierToken("Listener", + GeneratorUtils.SINGLE_WS_MINUTIAE, AbstractNodeFactory.createEmptyMinutiaeList()); QualifiedNameReferenceNode typeDescriptor = NodeFactory.createQualifiedNameReferenceNode(modulePrefix, AbstractNodeFactory.createToken(SyntaxKind.COLON_TOKEN), identifier); // Create variable - Token variableName = AbstractNodeFactory.createIdentifierToken(ep, SINGLE_WS_MINUTIAE, + Token variableName = AbstractNodeFactory.createIdentifierToken(ep, GeneratorUtils.SINGLE_WS_MINUTIAE, AbstractNodeFactory.createEmptyMinutiaeList()); // Create initializer - Token newKeyword = AbstractNodeFactory.createIdentifierToken(NEW); + Token newKeyword = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.NEW); Token literalToken = AbstractNodeFactory.createLiteralValueToken(SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN - , String.valueOf(port), SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); + , String.valueOf(port), GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE); BasicLiteralNode expression = NodeFactory.createBasicLiteralNode(SyntaxKind.NUMERIC_LITERAL, literalToken); PositionalArgumentNode portNode = NodeFactory.createPositionalArgumentNode(expression); - Token name = AbstractNodeFactory.createIdentifierToken(CONFIG); + Token name = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.CONFIG); SimpleNameReferenceNode argumentName = NodeFactory.createSimpleNameReferenceNode(name); - Token fieldName = AbstractNodeFactory.createIdentifierToken(HOST); + Token fieldName = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.HOST); Token literalHostToken = AbstractNodeFactory.createIdentifierToken('"' + host + '"', - SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE); + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE); BasicLiteralNode valueExpr = NodeFactory.createBasicLiteralNode(SyntaxKind.STRING_LITERAL, literalHostToken); MappingFieldNode hostNode = NodeFactory.createSpecificFieldNode(null, fieldName, @@ -140,8 +136,8 @@ public static ListenerDeclarationNode getListenerDeclarationNode(Integer port, S SeparatedNodeList fields = NodeFactory.createSeparatedNodeList(hostNode); MappingConstructorExpressionNode hostExpression = NodeFactory.createMappingConstructorExpressionNode( - AbstractNodeFactory.createToken(SyntaxKind.OPEN_BRACE_TOKEN), - fields, AbstractNodeFactory.createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); + AbstractNodeFactory.createToken(SyntaxKind.OPEN_BRACE_TOKEN), + fields, AbstractNodeFactory.createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); NamedArgumentNode namedArgumentNode = NodeFactory.createNamedArgumentNode(argumentName, AbstractNodeFactory.createToken(SyntaxKind.EQUAL_TOKEN), hostExpression); diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ParametersGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ParametersGenerator.java new file mode 100644 index 000000000..1fd9bffab --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ParametersGenerator.java @@ -0,0 +1,590 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +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.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; +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.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +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.createArrayTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createDefaultableParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; +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.OPEN_PAREN_TOKEN; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_PARAM_COMMENT; +import static io.ballerina.openapi.core.GeneratorConstants.NILLABLE; +import static io.ballerina.openapi.core.GeneratorUtils.convertOpenAPITypeToBallerina; +import static io.ballerina.openapi.core.GeneratorUtils.extractReferenceType; +import static io.ballerina.openapi.core.GeneratorUtils.getOpenAPIType; +import static io.ballerina.openapi.core.GeneratorUtils.getValidName; +import static io.ballerina.openapi.core.GeneratorUtils.isArraySchema; +import static io.ballerina.openapi.core.GeneratorUtils.isMapSchema; +import static io.ballerina.openapi.core.GeneratorUtils.isObjectSchema; +import static io.ballerina.openapi.core.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_103; +import static io.ballerina.openapi.core.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_104; +import static io.ballerina.openapi.core.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_105; +import static io.ballerina.openapi.core.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_106; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.getAnnotationNode; + +/** + * This class uses for generating all resource function parameters. + * + * @since 1.3.0 + */ +public class ParametersGenerator { + + private boolean isNullableRequired; + private final List requiredParams; + private final List defaultableParams; + private final OpenAPI openAPI; + + private static final List paramSupportedTypes = + new ArrayList<>(Arrays.asList(GeneratorConstants.INTEGER, GeneratorConstants.NUMBER, + GeneratorConstants.STRING, GeneratorConstants.BOOLEAN)); + + private static final List queryParamSupportedTypes = + new ArrayList<>(Arrays.asList(GeneratorConstants.INTEGER, GeneratorConstants.NUMBER, + GeneratorConstants.STRING, GeneratorConstants.BOOLEAN, GeneratorConstants.OBJECT)); + + public ParametersGenerator(boolean isNullableRequired, OpenAPI openAPI) { + this.isNullableRequired = isNullableRequired; + this.openAPI = openAPI; + this.requiredParams = new ArrayList<>(); + this.defaultableParams = new ArrayList<>(); + } + + public List getRequiredParams() { + return requiredParams; + } + + public List getDefaultableParams() { + return defaultableParams; + } + + public boolean isNullableRequired() { + return isNullableRequired; + } + + /** + * This function for generating operation parameters. + * + * @param operation OAS operation + * @throws BallerinaOpenApiException when the parameter generation fails. + */ + public void generateResourcesInputs(Map.Entry operation, + List resourceFunctionDocs) + throws BallerinaOpenApiException { + + Token comma = createToken(SyntaxKind.COMMA_TOKEN); + // Handle header and query parameters + if (operation.getValue().getParameters() != null) { + List parameters = operation.getValue().getParameters(); + for (Parameter parameter : parameters) { + Node param = null; + if (parameter.get$ref() != null) { + String referenceType = extractReferenceType(parameter.get$ref()); + parameter = openAPI.getComponents().getParameters().get(referenceType); + } + if (parameter.getIn().trim().equals(GeneratorConstants.HEADER)) { + param = handleHeader(parameter); + if (param.kind() == SyntaxKind.DEFAULTABLE_PARAM) { + defaultableParams.add(param); + defaultableParams.add(comma); + } else { + requiredParams.add(param); + requiredParams.add(comma); + } + } else if (parameter.getIn().trim().equals(GeneratorConstants.QUERY)) { + if (parameter.getRequired() != null && parameter.getRequired() && + (parameter.getSchema() != null && parameter.getSchema().getNullable() != null && + parameter.getSchema().getNullable())) { + isNullableRequired = true; + } + // type BasicType boolean|int|float|decimal|string ; + // public type () |BasicType|BasicType []| map; + param = createNodeForQueryParam(parameter); + if (param != null) { + if (param.kind() == SyntaxKind.DEFAULTABLE_PARAM) { + defaultableParams.add(param); + defaultableParams.add(comma); + } else { + requiredParams.add(param); + requiredParams.add(comma); + } + } + } + + if (param != null) { + String parameterName = param instanceof RequiredParameterNode ? + ((RequiredParameterNode) param).paramName().get().text() : + ((DefaultableParameterNode) param).paramName().get().text(); + String paramComment = parameter.getDescription() != null && !parameter.getDescription().isBlank() ? + parameter.getDescription() : DEFAULT_PARAM_COMMENT; + MarkdownParameterDocumentationLineNode paramAPIDoc = + DocCommentsGenerator.createAPIParamDoc(parameterName + , paramComment); + resourceFunctionDocs.add(paramAPIDoc); + } + } + } + } + + /** + * This function for generating parameter ST node for header. + *
 resource function get pets(@http:Header {name:"x-request-id"} string header) 
+ */ + private ParameterNode handleHeader(Parameter parameter) throws BallerinaOpenApiException { + + Schema schema = parameter.getSchema(); + String headerType; + TypeDescriptorNode headerTypeName; + IdentifierToken parameterName = createIdentifierToken(GeneratorUtils.escapeIdentifier(parameter.getName() + .toLowerCase(Locale.ENGLISH)), AbstractNodeFactory.createEmptyMinutiaeList(), + GeneratorUtils.SINGLE_WS_MINUTIAE); + + if (getOpenAPIType(schema) == null && schema.get$ref() == null) { + // Header example: + // 01.
+            //       in: header
+            //       name: X-Request-ID
+            //       schema: {}
+            //  
+ throw new BallerinaOpenApiException(String.format(OAS_SERVICE_106.getDescription(), parameter.getName())); + } else if (schema.get$ref() != null) { + String type = getValidName(extractReferenceType(schema.get$ref()), true); + Schema refSchema = openAPI.getComponents().getSchemas().get(type.trim()); + if (paramSupportedTypes.contains(getOpenAPIType(refSchema)) || + isArraySchema(refSchema)) { + headerType = type; + } else { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_105.getDescription(), + parameter.getName(), getOpenAPIType(refSchema))); + } + } else if (paramSupportedTypes.contains(getOpenAPIType(schema)) || isArraySchema(schema)) { + headerType = convertOpenAPITypeToBallerina(schema).trim(); + } else { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_105.getDescription(), + parameter.getName(), getOpenAPIType(schema))); + } + + if (isArraySchema(schema)) { + // TODO: Support nested arrays + Schema items = schema.getItems(); + String arrayType; + if (getOpenAPIType(items) == null && items.get$ref() == null) { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_104.getDescription(), + parameter.getName())); + } else if (items.get$ref() != null) { + String type = getValidName(extractReferenceType(items.get$ref()), true); + Schema refSchema = openAPI.getComponents().getSchemas().get(type.trim()); + if (paramSupportedTypes.contains(getOpenAPIType(refSchema))) { + arrayType = type; + } else { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_103.getDescription(), + parameter.getName(), type)); + } + } else if (!paramSupportedTypes.contains(getOpenAPIType(items))) { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_103.getDescription(), + parameter.getName(), getOpenAPIType(items))); + } else if (items.getEnum() != null && !items.getEnum().isEmpty()) { + arrayType = OPEN_PAREN_TOKEN.stringValue() + convertOpenAPITypeToBallerina(items) + + CLOSE_PAREN_TOKEN.stringValue(); + } else { + arrayType = GeneratorUtils.convertOpenAPITypeToBallerina(items); + } + BuiltinSimpleNameReferenceNode headerArrayItemTypeName = createBuiltinSimpleNameReferenceNode( + null, createIdentifierToken(arrayType)); + ArrayDimensionNode dimensionNode = + NodeFactory.createArrayDimensionNode(createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + NodeList nodeList = createNodeList(dimensionNode); + headerTypeName = createArrayTypeDescriptorNode(headerArrayItemTypeName, nodeList); + } else { + headerTypeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken( + headerType, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE)); + } + // Create annotation for header + // TODO: This code block is to be enabled when handle the headers handle additional parameters + // MappingConstructorExpressionNode annotValue = NodeFactory.createMappingConstructorExpressionNode( + // createToken(SyntaxKind.OPEN_BRACE_TOKEN), NodeFactory.createSeparatedNodeList(), + // createToken(SyntaxKind.CLOSE_BRACE_TOKEN)); + + AnnotationNode headerNode = getAnnotationNode(GeneratorConstants.HEADER_ANNOT, null); + NodeList headerAnnotations = createNodeList(headerNode); + // Handle optional values in headers + if (!parameter.getRequired()) { + // If optional it behaves like default value with null ex:(string? header) + // If schema has an enum and that has a null values then the type is already nill. Hence, the check. + headerTypeName = headerTypeName.toString().trim().endsWith(NILLABLE) ? headerTypeName : + createOptionalTypeDescriptorNode(headerTypeName, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + } + // Handle default values in headers + if (schema.getDefault() != null) { + return getDefaultableHeaderNode(schema, headerTypeName, parameterName, headerAnnotations); + } + // Handle header with parameter required true and nullable ture ex: (string? header) + if (parameter.getRequired() && schema.getNullable() != null && schema.getNullable().equals(true)) { + isNullableRequired = true; + headerTypeName = headerTypeName.toString().trim().endsWith(NILLABLE) ? headerTypeName : + createOptionalTypeDescriptorNode(headerTypeName, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + } + return createRequiredParameterNode(headerAnnotations, headerTypeName, parameterName); + } + + /** + * Generate ballerina default headers. + */ + private DefaultableParameterNode getDefaultableHeaderNode(Schema schema, TypeDescriptorNode headerTypeName, + IdentifierToken parameterName, + NodeList headerAnnotations) { + + if (!getOpenAPIType(schema).equals(GeneratorConstants.ARRAY)) { + return createDefaultableParameterNode(headerAnnotations, headerTypeName, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken("\"" + + schema.getDefault().toString() + "\""))); + } + return createDefaultableParameterNode(headerAnnotations, headerTypeName, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); + } + + /** + * This for generate query parameter nodes. + *

+ * Ballerina support query parameter types : + * type BasicType boolean|int|float|decimal|string ; + * public type QueryParamType json | () |BasicType|BasicType[]; + */ + private Node createNodeForQueryParam(Parameter parameter) throws BallerinaOpenApiException { + + Schema schema = parameter.getSchema(); + NodeList annotations = createEmptyNodeList(); + IdentifierToken parameterName = createIdentifierToken( + GeneratorUtils.escapeIdentifier(parameter.getName().trim()), + AbstractNodeFactory.createEmptyMinutiaeList(), GeneratorUtils.SINGLE_WS_MINUTIAE); + boolean isSchemaNotSupported = schema == null || getOpenAPIType(schema) == null; + //Todo: will enable when header parameter support objects + //paramSupportedTypes.add(GeneratorConstants.OBJECT); + if (schema != null && schema.get$ref() != null) { + String type = getValidName(extractReferenceType(schema.get$ref()), true); + Schema refSchema = openAPI.getComponents().getSchemas().get(type); + return handleReferencedQueryParameter(parameter, type, refSchema, annotations, parameterName); + } else if (parameter.getContent() != null) { + Content content = parameter.getContent(); + for (Map.Entry mediaTypeEntry : content.entrySet()) { + return handleMapJsonQueryParameter(parameter, annotations, parameterName, mediaTypeEntry); + } + } else if (isSchemaNotSupported) { + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; + throw new BallerinaOpenApiException(String.format(messages.getDescription(), + getOpenAPIType(parameter.getSchema()))); + } else if (parameter.getSchema().getDefault() != null) { + // When query parameter has default value + return handleDefaultQueryParameter(schema, annotations, parameterName); + } else if (parameter.getRequired() && schema.getNullable() == null) { + // Required typeDescriptor + return handleRequiredQueryParameter(schema, annotations, parameterName); + } else { + // Optional typeDescriptor + return handleOptionalQueryParameter(schema, annotations, parameterName); + } + return null; + } + + /** + * Handle query parameter for content type which has application/json. + * example: + *

+     *     parameters:
+     *         - name: petType
+     *           in: query
+     *           content:
+     *             application/json:
+     *               schema:
+     *                 type: object
+     *                 additionalProperties: true
+     * 
+ */ + private RequiredParameterNode handleMapJsonQueryParameter(Parameter parameter, NodeList annotations, + IdentifierToken parameterName, + Map.Entry mediaTypeEntry) + throws BallerinaOpenApiException { + + Schema parameterSchema; + if (mediaTypeEntry.getValue().getSchema() != null && + mediaTypeEntry.getValue().getSchema().get$ref() != null) { + String type = getValidName(extractReferenceType(mediaTypeEntry.getValue().getSchema().get$ref()), true); + parameterSchema = (Schema) openAPI.getComponents().getSchemas().get(type.trim()); + } else { + parameterSchema = mediaTypeEntry.getValue().getSchema(); + } + + if (mediaTypeEntry.getKey().equals(GeneratorConstants.APPLICATION_JSON) && + isMapSchema(parameterSchema)) { + if (parameter.getRequired()) { + BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(GeneratorConstants.MAP_JSON)); + return createRequiredParameterNode(annotations, rTypeName, parameterName); + } else { + BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(GeneratorConstants.MAP_JSON)); + OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(rTypeName, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + return createRequiredParameterNode(annotations, optionalNode, parameterName); + } + } else { + String type = GeneratorUtils.getBallerinaMediaType(mediaTypeEntry.getKey(), false); + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; + throw new BallerinaOpenApiException(String.format(messages.getDescription(), + type)); + } + } + + /** + * This function is to handle query schema which is not have required true. + */ + private Node handleOptionalQueryParameter(Schema schema, NodeList annotations, + IdentifierToken parameterName) throws BallerinaOpenApiException { + + if (isArraySchema(schema)) { + Schema items = schema.getItems(); + if (getOpenAPIType(items) == null && items.get$ref() == null) { + // Resource function doesn't support to query parameters with array type which doesn't have an + // item type. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; + throw new BallerinaOpenApiException(messages.getDescription()); + } else if ((!(isObjectSchema(items)) && !(getOpenAPIType(items) != null && + getOpenAPIType(items).equals(GeneratorConstants.ARRAY))) + || items.get$ref() != null) { + // create arrayTypeDescriptor + ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); + OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(arrayTypeName, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + return createRequiredParameterNode(annotations, optionalNode, parameterName); + } else if (getOpenAPIType(items).equals(GeneratorConstants.ARRAY)) { + // Resource function doesn't support to the nested array type query parameters. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; + throw new BallerinaOpenApiException(messages.getDescription()); + } else { + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; + throw new BallerinaOpenApiException(String.format(messages.getDescription(), "object")); + } + } else { + Token name = getQueryParamTypeToken(schema); + TypeDescriptorNode queryParamType = createBuiltinSimpleNameReferenceNode(null, name); + // If schema has an enum with null value, the type is already nil. Hence, the check. + if (!name.text().trim().endsWith(NILLABLE)) { + queryParamType = createOptionalTypeDescriptorNode(queryParamType, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + } + return createRequiredParameterNode(annotations, queryParamType, parameterName); + } + } + + private Node handleReferencedQueryParameter(Parameter parameter, String refTypeName, Schema refSchema, + NodeList annotations, IdentifierToken parameterName) { + BuiltinSimpleNameReferenceNode refTypeNameNode = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(refTypeName)); + if (refSchema.getDefault() != null) { + String defaultValue = getOpenAPIType(refSchema).equals(GeneratorConstants.STRING) ? + String.format("\"%s\"", refSchema.getDefault().toString()) : refSchema.getDefault().toString(); + return createDefaultableParameterNode(annotations, refTypeNameNode, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(defaultValue))); + } else if (parameter.getRequired() && (refSchema.getNullable() == null || (!refSchema.getNullable()))) { + return createRequiredParameterNode(annotations, refTypeNameNode, parameterName); + } else { + OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(refTypeNameNode, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + return createRequiredParameterNode(annotations, optionalNode, parameterName); + } + } + + private Node handleRequiredQueryParameter(Schema schema, NodeList annotations, + IdentifierToken parameterName) throws BallerinaOpenApiException { + + if (isArraySchema(schema)) { + Schema items = schema.getItems(); + if (!(isArraySchema(items)) && (getOpenAPIType(items) != null || (items.get$ref() != null))) { + ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); + return createRequiredParameterNode(annotations, arrayTypeName, parameterName); + } else if (getOpenAPIType(items) == null) { + // Resource function doesn't support query parameters for array types that doesn't have an item type. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; + throw new BallerinaOpenApiException(messages.getDescription()); + } else if (isObjectSchema(items)) { + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; + throw new BallerinaOpenApiException(String.format(messages.getDescription(), "object")); + } else { + // Resource function doesn't support to the nested array type query parameters. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; + throw new BallerinaOpenApiException(messages.getDescription()); + } + } else { + Token name = getQueryParamTypeToken(schema); + BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, name); + return createRequiredParameterNode(annotations, rTypeName, parameterName); + } + } + + /** + * This function generate default query parameter when OAS gives default value. + *

+ * OAS code example: + *

+     *      parameters:
+     *         - name: limit
+     *           in: query
+     *           schema:
+     *             type: integer
+     *             default: 10
+     *             format: int32
+     *  
+ * generated ballerina -> int limit = 10; + */ + + private Node handleDefaultQueryParameter(Schema schema, NodeList annotations, + IdentifierToken parameterName) throws BallerinaOpenApiException { + + if (isArraySchema(schema)) { + Schema items = schema.getItems(); + if (!isArraySchema(items) && (getOpenAPIType(items) != null || (items.get$ref() != null))) { + ArrayTypeDescriptorNode arrayTypeName = getArrayTypeDescriptorNode(items); + return createDefaultableParameterNode(annotations, arrayTypeName, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); + } else if (getOpenAPIType(items) == null) { + // Resource function doesn't support to query parameters with array type which hasn't item type. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_101; + throw new BallerinaOpenApiException(messages.getDescription()); + } else { + // Resource function doesn't support to the nested array type query parameters. + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_100; + throw new BallerinaOpenApiException(messages.getDescription()); + } + } else { + Token name = getQueryParamTypeToken(schema); + BuiltinSimpleNameReferenceNode rTypeName = createBuiltinSimpleNameReferenceNode(null, name); + if (getOpenAPIType(schema).equals(GeneratorConstants.STRING)) { + return createDefaultableParameterNode(annotations, rTypeName, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken('"' + + schema.getDefault().toString() + '"'))); + } + return createDefaultableParameterNode(annotations, rTypeName, parameterName, + createToken(SyntaxKind.EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(schema.getDefault().toString()))); + } + } + + private static Token getQueryParamTypeToken(Schema schema) throws BallerinaOpenApiException { + if (schema instanceof MapSchema) { + // handle inline record open + RecordTypeGenerator recordTypeGenerator = new RecordTypeGenerator(schema, null); + TypeDescriptorNode recordNode = recordTypeGenerator.generateTypeDescriptorNode(); + return createIdentifierToken(recordNode.toSourceCode(), + GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + } else { + return createIdentifierToken(GeneratorUtils.convertOpenAPITypeToBallerina(schema), + GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + } + } + + // Create ArrayTypeDescriptorNode using Schema + private ArrayTypeDescriptorNode getArrayTypeDescriptorNode(Schema items) throws BallerinaOpenApiException { + String arrayName; + if (items.get$ref() != null) { + String referenceType = extractReferenceType(items.get$ref()); + String type = getValidName(referenceType, true); + Schema refSchema = openAPI.getComponents().getSchemas().get(type); + if (queryParamSupportedTypes.contains(getOpenAPIType(refSchema))) { + arrayName = type; + } else { + ServiceDiagnosticMessages messages = ServiceDiagnosticMessages.OAS_SERVICE_102; + throw new BallerinaOpenApiException(String.format(messages.getDescription(), type)); + } + } else { + arrayName = GeneratorUtils.convertOpenAPITypeToBallerina(items); + if (items.getEnum() != null && !items.getEnum().isEmpty()) { + arrayName = OPEN_PAREN_TOKEN.stringValue() + arrayName + CLOSE_PAREN_TOKEN.stringValue(); + } + } + Token arrayNameToken = createIdentifierToken(arrayName, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + BuiltinSimpleNameReferenceNode memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, arrayNameToken); + ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + NodeList nodeList = createNodeList(dimensionNode); + + if (items.getNullable() != null && items.getNullable() && items.getEnum() == null) { + // generate -> int?[] + OptionalTypeDescriptorNode optionalNode = createOptionalTypeDescriptorNode(memberTypeDesc, + createToken(SyntaxKind.QUESTION_MARK_TOKEN)); + return createArrayTypeDescriptorNode(optionalNode, nodeList); + } + // generate -> int[] + return createArrayTypeDescriptorNode(memberTypeDesc, nodeList); + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/RequestBodyGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/RequestBodyGenerator.java new file mode 100644 index 000000000..25a6339c7 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/RequestBodyGenerator.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +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.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.parameters.RequestBody; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; + +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.createArrayTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_REQUEST; +import static io.ballerina.openapi.core.GeneratorConstants.MAP_STRING; +import static io.ballerina.openapi.core.GeneratorConstants.PAYLOAD; +import static io.ballerina.openapi.core.GeneratorConstants.PIPE; +import static io.ballerina.openapi.core.GeneratorConstants.REQUEST; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.extractReferenceType; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.getAnnotationNode; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.handleMediaType; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.selectMediaType; + +/** + * This class for generating request body payload for OAS requestBody section. + * + * @since 1.3.0 + */ +public class RequestBodyGenerator { + private final RequestBody requestBody; + + public RequestBodyGenerator(RequestBody requestBody) { + this.requestBody = requestBody; + } + + /** + * This for creating request Body for given request object. + */ + public RequiredParameterNode createNodeForRequestBody() throws BallerinaOpenApiException { + // type CustomRecord record {| anydata...; |}; + // public type PayloadType string|json|xml|byte[]|CustomRecord|CustomRecord[] ; + Optional typeName; + // Filter same data type + HashSet types = new HashSet<>(); + for (Map.Entry mime : requestBody.getContent().entrySet()) { + typeName = getNodeForPayloadType(mime); + if (typeName.isPresent()) { + types.add(typeName.get().toString()); + } else { + types.add(HTTP_REQUEST); + } + } + if (types.size() > 1 && types.contains(HTTP_REQUEST)) { + typeName = Optional.of(NodeParser.parseTypeDescriptor(HTTP_REQUEST)); + } else if (types.size() > 1) { + String result = String.join(PIPE, types); + typeName = Optional.of(NodeParser.parseTypeDescriptor(result)); + } else { + typeName = Optional.of(NodeParser.parseTypeDescriptor(types.iterator().next())); + } + AnnotationNode annotationNode = getAnnotationNode(GeneratorConstants.PAYLOAD_KEYWORD, null); + NodeList annotation = NodeFactory.createNodeList(annotationNode); + String paramName = typeName.get().toString().equals(HTTP_REQUEST) ? REQUEST : PAYLOAD; + + if (typeName.get().toString().equals(HTTP_REQUEST)) { + return createRequiredParameterNode(createEmptyNodeList(), + createSimpleNameReferenceNode(createIdentifierToken(HTTP_REQUEST)), createIdentifierToken(REQUEST)); + } + return createRequiredParameterNode(annotation, typeName.get(), createIdentifierToken(paramName, + GeneratorUtils.SINGLE_WS_MINUTIAE, GeneratorUtils.SINGLE_WS_MINUTIAE)); + } + + /** + * This util function is for generating type node for request payload in resource function. + */ + private Optional getNodeForPayloadType(Map.Entry mediaType) + throws BallerinaOpenApiException { + + Optional typeName; + if (mediaType.getValue() != null && mediaType.getValue().getSchema() != null && + mediaType.getValue().getSchema().get$ref() != null) { + String reference = mediaType.getValue().getSchema().get$ref(); + String schemaName = GeneratorUtils.getValidName(extractReferenceType(reference), true); + String mediaTypeContent = selectMediaType(mediaType.getKey().trim()); + IdentifierToken identifierToken; + switch (mediaTypeContent) { + case GeneratorConstants.APPLICATION_XML: + identifierToken = createIdentifierToken(GeneratorConstants.XML); + typeName = Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)); + break; + case GeneratorConstants.TEXT: + identifierToken = createIdentifierToken(schemaName); + typeName = Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)); + break; + case GeneratorConstants.APPLICATION_OCTET_STREAM: + ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + typeName = Optional.ofNullable(createArrayTypeDescriptorNode(createBuiltinSimpleNameReferenceNode( + null, createIdentifierToken(GeneratorConstants.BYTE)), + NodeFactory.createNodeList(dimensionNode))); + break; + case GeneratorConstants.APPLICATION_JSON: + typeName = Optional.ofNullable(createSimpleNameReferenceNode(createIdentifierToken(schemaName))); + break; + case GeneratorConstants.APPLICATION_URL_ENCODE: + typeName = Optional.ofNullable(createSimpleNameReferenceNode(createIdentifierToken(MAP_STRING))); + //Commented due to the data binding issue in the ballerina http module + //TODO: Related issue:https://github.com/ballerina-platform/ballerina-standard-library/issues/4090 +// typeName = Optional.ofNullable(createSimpleNameReferenceNode(createIdentifierToken( +// GeneratorUtils.getValidName(schemaName, true)))); + break; + default: + ImmutablePair, Optional> mediaTypeTokens = + handleMediaType(mediaType, null); + if (mediaTypeTokens.getLeft().isPresent()) { + typeName = mediaTypeTokens.getLeft(); + } else { + identifierToken = createIdentifierToken(HTTP_REQUEST); + typeName = Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)); + } + } + } else { + ImmutablePair, Optional> mediaTypeTokens = + handleMediaType(mediaType, null); + typeName = mediaTypeTokens.left; + } + return typeName; + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ReturnTypeGenerator.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ReturnTypeGenerator.java new file mode 100644 index 000000000..56745cd9c --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ReturnTypeGenerator.java @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +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.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.RecordFieldNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +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.TypeReferenceNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.document.DocCommentsGenerator; +import io.ballerina.openapi.core.generators.schema.BallerinaTypesGenerator; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.media.Content; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +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.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.createRecordFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRecordTypeDescriptorNode; +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.createTypeDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_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.openapi.core.GeneratorConstants.ANYDATA; +import static io.ballerina.openapi.core.GeneratorConstants.DEFAULT_RETURN_COMMENT; +import static io.ballerina.openapi.core.GeneratorConstants.ERROR; +import static io.ballerina.openapi.core.GeneratorConstants.HTTP_RESPONSE; +import static io.ballerina.openapi.core.GeneratorConstants.PIPE; +import static io.ballerina.openapi.core.GeneratorConstants.POST; +import static io.ballerina.openapi.core.GeneratorConstants.RESPONSE_RECORD_NAME; +import static io.ballerina.openapi.core.GeneratorConstants.RETURNS; +import static io.ballerina.openapi.core.generators.service.ServiceDiagnosticMessages.OAS_SERVICE_107; +import static io.ballerina.openapi.core.generators.service.ServiceGenerationUtils.handleMediaType; + +/** + * This class for generating return type definition node according to the OpenAPI specification response section. + * + * @since 1.3.0 + */ +public class ReturnTypeGenerator { + + private final BallerinaTypesGenerator ballerinaSchemaGenerator; + private final String pathRecord; + private static int countForRecord = 0; + private String httpMethod; + private OpenAPI openAPI; + + private final Map typeInclusionRecords = new HashMap<>(); + + public Map getTypeInclusionRecords() { + return this.typeInclusionRecords; + } + + public static void setCount(int count) { + ReturnTypeGenerator.countForRecord = count; + } + + public void setCountForRecord(int count) { + setCount(count); + } + + public ReturnTypeGenerator(BallerinaTypesGenerator ballerinaSchemaGenerator, String pathRecord, OpenAPI openAPI) { + this.ballerinaSchemaGenerator = ballerinaSchemaGenerator; + this.pathRecord = pathRecord; + this.openAPI = openAPI; + } + + /** + * This function used to generate return function node in the function signature. + * Payload media type will not be added to the annotation. + * + * @param operation OpenApi operation + * @param annotations Annotation node list + * @return return returnNode + * @throws BallerinaOpenApiException + */ + public ReturnTypeDescriptorNode getReturnTypeDescriptorNode(Map.Entry operation, + NodeList annotations, String path, + List resourceFunctionDocs) + throws BallerinaOpenApiException { + + ReturnTypeDescriptorNode returnNode; + List returnDescriptions = new ArrayList<>(); + httpMethod = operation.getKey().name().toLowerCase(Locale.ENGLISH); + if (operation.getValue().getResponses() != null) { + ApiResponses responses = operation.getValue().getResponses(); + if (responses.size() > 1) { + //handle multiple response scenarios ex: status code 200, 400, 500 + TypeDescriptorNode type = handleMultipleResponse(responses, returnDescriptions); + returnNode = createReturnTypeDescriptorNode(createToken(RETURNS_KEYWORD), annotations, type); + } else if (responses.size() == 1) { + //handle single response + Iterator> responseIterator = responses.entrySet().iterator(); + Map.Entry response = responseIterator.next(); + returnNode = handleSingleResponse(annotations, response); + // checks `ifEmpty` not `ifBlank` because user can intentionally set the description to empty string + if (response.getValue().getDescription() != null && !response.getValue().getDescription().isEmpty()) { + returnDescriptions.add(response.getValue().getDescription()); + } else { + // need to discuss + returnDescriptions.add(DEFAULT_RETURN_COMMENT); + } + } else { + TypeDescriptorNode defaultType = createSimpleNameReferenceNode(createIdentifierToken(HTTP_RESPONSE)); + returnNode = createReturnTypeDescriptorNode(createToken(RETURNS_KEYWORD), annotations, defaultType); + returnDescriptions.add(HTTP_RESPONSE); + } + } else { + // --error node TypeDescriptor + returnNode = createReturnTypeDescriptorNode(createToken(SyntaxKind.RETURNS_KEYWORD), createEmptyNodeList(), + createSimpleNameReferenceNode(createIdentifierToken("error?"))); + returnDescriptions.add(ERROR); + } + + // Add return description to the resource function + if (returnDescriptions.size() > 1) { + StringBuilder returnDescriptionForUnions = new StringBuilder( + "# + return - returns can be any of following types\n"); + String typeDescriptionTemplate = "# %s (%s)%n"; + for (String description : returnDescriptions) { + String[] values = description.split("\\|"); + // Replace new lines and tabs in the description by space. + String responseDescription = values[1].replaceAll("[\\r\\n\\t]", " "); + returnDescriptionForUnions.append(String.format(typeDescriptionTemplate, + values[0], responseDescription)); + } + String dummyTypeWithDescription = returnDescriptionForUnions.toString() + "type a A;"; + ModuleMemberDeclarationNode moduleMemberDeclarationNode = NodeParser.parseModuleMemberDeclaration( + dummyTypeWithDescription); + TypeDefinitionNode typeDefinitionNode = (TypeDefinitionNode) moduleMemberDeclarationNode; + MetadataNode metadataNode = typeDefinitionNode.metadata().get(); + MarkdownDocumentationNode returnDoc = (MarkdownDocumentationNode) metadataNode.children().get(0); + resourceFunctionDocs.add(returnDoc); + } else { + MarkdownParameterDocumentationLineNode returnDoc = + DocCommentsGenerator.createAPIParamDoc(RETURN_KEYWORD.stringValue(), returnDescriptions.get(0)); + resourceFunctionDocs.add(returnDoc); + } + + if (GeneratorUtils.isComplexURL(path)) { + assert returnNode != null; + String returnStatement = returnNode.toString().trim().replace(RETURNS, "") + "|error"; + return createReturnTypeDescriptorNode(createToken(SyntaxKind.RETURNS_KEYWORD), createEmptyNodeList(), + createSimpleNameReferenceNode(createIdentifierToken(returnStatement))); + } + return returnNode; + } + + /** + * This util is to generate return node when the operation has one response. + */ + private ReturnTypeDescriptorNode handleSingleResponse(NodeList annotations, + Map.Entry response) + throws BallerinaOpenApiException { + + ReturnTypeDescriptorNode returnNode = null; + Token returnKeyWord = createToken(RETURNS_KEYWORD); + ApiResponse responseValue = response.getValue(); + Content responseContent = responseValue.getContent(); + + if (responseContent == null && responseValue.get$ref() == null || + (responseContent != null && responseContent.size() == 0)) { + // response has single response without content type or not having reference response. + String code = GeneratorConstants.HTTP_CODES_DES.get(response.getKey().trim()); + TypeDescriptorNode statues; + if (response.getKey().trim().equals(GeneratorConstants.DEFAULT)) { + statues = createSimpleNameReferenceNode(createIdentifierToken(HTTP_RESPONSE)); + } else { + statues = GeneratorUtils.getQualifiedNameReferenceNode(GeneratorConstants.HTTP, code); + } + returnNode = createReturnTypeDescriptorNode(returnKeyWord, annotations, statues); + } else if (responseContent != null) { + // when the response has content values + String responseCode = response.getKey().trim(); + boolean isWithOutStatusCode = + (httpMethod.equals(POST) && responseCode.equals(GeneratorConstants.HTTP_201)) || + (!httpMethod.equals(POST) && responseCode.equals(GeneratorConstants.HTTP_200)); + if (isWithOutStatusCode) { + // handle 200, 201 status code + Set> contentEntries = responseContent.entrySet(); + returnNode = getReturnNodeForSchemaType(contentEntries); + } else if (response.getKey().trim().equals(GeneratorConstants.DEFAULT)) { + // handle status code with `default`, this maps to `http:Response` + BuiltinSimpleNameReferenceNode type = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(HTTP_RESPONSE)); + returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), type); + } else { + // handle rest of the status codes + String code = GeneratorConstants.HTTP_CODES_DES.get(response.getKey().trim()); + TypeDescriptorNode type; + + if (responseContent.entrySet().size() > 1) { + // handle multiple media types + type = handleMultipleContents(responseContent.entrySet()); + } else { + // handle single media type + Iterator> contentItr = responseContent.entrySet().iterator(); + Map.Entry mediaTypeEntry = contentItr.next(); + String recordName = getNewRecordName(); + ImmutablePair, Optional> mediaTypeToken = + handleMediaType(mediaTypeEntry, recordName); + Optional rightNode = mediaTypeToken.right; + if (rightNode.isPresent()) { + typeInclusionRecords.put(recordName, rightNode.get()); + setCountForRecord(countForRecord++); + type = createSimpleNameReferenceNode(createIdentifierToken(recordName)); + } else { + type = mediaTypeToken.left.orElseGet( + () -> createSimpleNameReferenceNode(createIdentifierToken(ANYDATA))); + } + } + if (!type.toString().equals(HTTP_RESPONSE)) { + SimpleNameReferenceNode recordType = createReturnTypeInclusionRecord(code, type); + NodeList annotation = createEmptyNodeList(); + returnNode = createReturnTypeDescriptorNode(returnKeyWord, annotation, recordType); + } + } + } + return returnNode; + } + + /** + * This util function is for handling the response which has 200 status code with content types. + * + * @param contentEntries collection of content entries + */ + private ReturnTypeDescriptorNode getReturnNodeForSchemaType(Set> contentEntries) + throws BallerinaOpenApiException { + + Token returnKeyWord = createToken(RETURNS_KEYWORD); + ReturnTypeDescriptorNode returnNode = null; + + int contentTypeNumber = contentEntries.size(); + if (contentTypeNumber > 1) { + TypeDescriptorNode type = handleMultipleContents(contentEntries); + returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), type); + } else { + for (Map.Entry next : contentEntries) { + String recordName = getNewRecordName(); + ImmutablePair, Optional> + mediaTypeToken = handleMediaType(next, recordName); + // right node represents the newly generated node for if there is an inline record in the returned + // tuple. + Optional rightNode = mediaTypeToken.right; + + if (rightNode.isPresent()) { + typeInclusionRecords.put(recordName, rightNode.get()); + setCountForRecord(countForRecord++); + SimpleNameReferenceNode type = createSimpleNameReferenceNode(createIdentifierToken(recordName)); + returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), type); + } else { + TypeDescriptorNode returnType; + returnType = mediaTypeToken.left.orElseGet( + () -> createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(ANYDATA))); + returnNode = createReturnTypeDescriptorNode(returnKeyWord, createEmptyNodeList(), returnType); + } + } + } + return returnNode; + } + + /** + * Generate union type node when operation has multiple responses. + */ + private TypeDescriptorNode handleMultipleResponse(ApiResponses responses, List returnDescription) + throws BallerinaOpenApiException { + + Set qualifiedNodes = new LinkedHashSet<>(); + + for (Map.Entry response : responses.entrySet()) { + String responseCode = response.getKey().trim(); + String code = GeneratorConstants.HTTP_CODES_DES.get(responseCode); + ApiResponse responseValue = response.getValue(); + Content content = responseValue != null ? responseValue.getContent() : null; + String typeName = null; + + if (code == null && !responseCode.equals(GeneratorConstants.DEFAULT)) { + throw new BallerinaOpenApiException(String.format(OAS_SERVICE_107.getDescription(), responseCode)); + } + if (responseValue != null && responseValue.get$ref() != null) { + String[] splits = responseValue.get$ref().split("/"); + String extractReferenceType = splits[splits.length - 1]; + responseValue = openAPI.getComponents().getResponses().get(extractReferenceType); + content = responseValue.getContent(); + } + if (responseCode.equals(GeneratorConstants.DEFAULT)) { + TypeDescriptorNode record = createSimpleNameReferenceNode(createIdentifierToken(HTTP_RESPONSE)); + typeName = record.toSourceCode(); + } else if (content == null && (responseValue == null || responseValue.get$ref() == null) || + content != null && content.size() == 0) { + //key and value + QualifiedNameReferenceNode node = GeneratorUtils.getQualifiedNameReferenceNode(GeneratorConstants.HTTP, + code); + typeName = node.toSourceCode(); + } else if (content != null) { + TypeDescriptorNode bodyType = handleMultipleContents(content.entrySet()); + //Check the default behaviour for return type according to POST method. + boolean isWithOutStatusCode = + (httpMethod.equals(POST) && responseCode.equals(GeneratorConstants.HTTP_201)) || + (!httpMethod.equals(POST) && responseCode.equals(GeneratorConstants.HTTP_200)); + if (isWithOutStatusCode) { + typeName = bodyType.toSourceCode(); + } else { + SimpleNameReferenceNode node = createReturnTypeInclusionRecord(code, bodyType); + typeName = node.name().text(); + } + } + if (typeName != null) { + qualifiedNodes.add(typeName); + if (responseValue.getDescription() != null && !responseValue.getDescription().isEmpty()) { + returnDescription.add(typeName.trim() + PIPE + responseValue.getDescription().trim()); + } + } + } + + String unionType = String.join(PIPE, qualifiedNodes); + if (qualifiedNodes.contains(ANYDATA)) { + return NodeParser.parseTypeDescriptor(ANYDATA); + } + return NodeParser.parseTypeDescriptor(unionType); + } + + /** + * Generate union type node when response has multiple content types. + */ + private TypeDescriptorNode handleMultipleContents(Set> contentEntries) + throws BallerinaOpenApiException { + Set qualifiedNodes = new LinkedHashSet<>(); + for (Map.Entry contentType : contentEntries) { + String recordName = getNewRecordName(); + ImmutablePair, Optional> mediaTypeToken = + handleMediaType(contentType, recordName); + + Optional leftNode = mediaTypeToken.left; + Optional rightNode = mediaTypeToken.right; + + if (leftNode.isEmpty()) { + SimpleNameReferenceNode httpResponse = createSimpleNameReferenceNode(createIdentifierToken(ANYDATA)); + qualifiedNodes.add(httpResponse.name().text()); + } else if (rightNode.isPresent()) { + typeInclusionRecords.put(recordName, rightNode.get()); + setCountForRecord(countForRecord++); + qualifiedNodes.add(createSimpleNameReferenceNode(createIdentifierToken(recordName)).toSourceCode()); + } else { + TypeDescriptorNode typeDescriptorNode = leftNode.get(); + qualifiedNodes.add(typeDescriptorNode.toSourceCode()); + } + } + + if (qualifiedNodes.size() == 1) { + return NodeParser.parseTypeDescriptor(qualifiedNodes.iterator().next()); + } + String unionType = String.join(PIPE, qualifiedNodes); + if (qualifiedNodes.contains(ANYDATA)) { + return NodeParser.parseTypeDescriptor(ANYDATA); + } + return NodeParser.parseTypeDescriptor(unionType); + } + + private String getNewRecordName() { + return countForRecord == 0 ? pathRecord + RESPONSE_RECORD_NAME : pathRecord + "Response_" + countForRecord; + } + + /** + * Create recordType TypeDescriptor. + */ + private SimpleNameReferenceNode createReturnTypeInclusionRecord(String statusCode, TypeDescriptorNode type) { + + String recordName = statusCode + GeneratorUtils.getValidName(type.toString(), true); + Token recordKeyWord = createToken(RECORD_KEYWORD); + Token bodyStartDelimiter = createIdentifierToken("{|"); + // Create record fields + List recordFields = new ArrayList<>(); + // Type reference node + Token asteriskToken = createIdentifierToken("*"); + QualifiedNameReferenceNode typeNameField = GeneratorUtils.getQualifiedNameReferenceNode(GeneratorConstants.HTTP, + statusCode); + TypeReferenceNode typeReferenceNode = createTypeReferenceNode( + asteriskToken, + typeNameField, + createToken(SyntaxKind.SEMICOLON_TOKEN)); + recordFields.add(typeReferenceNode); + + IdentifierToken fieldName = createIdentifierToken(GeneratorConstants.BODY, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE); + RecordFieldNode recordFieldNode = createRecordFieldNode( + null, null, + type, + fieldName, null, + createToken(SyntaxKind.SEMICOLON_TOKEN)); + recordFields.add(recordFieldNode); + + NodeList fieldsList = createSeparatedNodeList(recordFields); + Token bodyEndDelimiter = createIdentifierToken("|}"); + + RecordTypeDescriptorNode recordTypeDescriptorNode = createRecordTypeDescriptorNode( + recordKeyWord, + bodyStartDelimiter, + fieldsList, null, + bodyEndDelimiter); + + TypeDefinitionNode typeDefinitionNode = createTypeDefinitionNode(null, + createToken(PUBLIC_KEYWORD), + createToken(TYPE_KEYWORD), + createIdentifierToken(recordName), + recordTypeDescriptorNode, + createToken(SEMICOLON_TOKEN)); + + typeInclusionRecords.put(recordName, typeDefinitionNode); + + return createSimpleNameReferenceNode(createIdentifierToken(recordName)); + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceDiagnosticMessages.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceDiagnosticMessages.java similarity index 68% rename from openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceDiagnosticMessages.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceDiagnosticMessages.java index 9000a078d..79c02fe0c 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/generators/service/ServiceDiagnosticMessages.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceDiagnosticMessages.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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 + * 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. + * 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.openapi.generators.service; +package io.ballerina.openapi.core.generators.service; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -24,7 +24,7 @@ * This {@code ServiceDiagnosticMessages} enum class for containing the error message related to openapi to ballerina * service generation command. * - * @since 2.0.0 + * @since 1.3.0 */ public enum ServiceDiagnosticMessages { OAS_SERVICE_100("OAS_SERVICE_100", "Query parameters with nested array types are not " + @@ -33,7 +33,9 @@ public enum ServiceDiagnosticMessages { "Query parameters with no array item type can not be mapped to Ballerina resource" + " query parameters.", DiagnosticSeverity.ERROR), OAS_SERVICE_102("OAS_SERVICE_102", - "Query parameters with type '%s' can not be mapped to the Ballerina query parameters.", + "Type '%s' is not a valid query parameter type in Ballerina. " + + "The supported types are string, int, float, boolean, decimal, array types of the aforementioned " + + "types and map.", DiagnosticSeverity.ERROR), OAS_SERVICE_103("OAS_SERVICE_103", "Header '%s' with array item type: '%s' is not " + "supported in Ballerina.", DiagnosticSeverity.ERROR), @@ -47,7 +49,7 @@ public enum ServiceDiagnosticMessages { "Header '%s' with no header type can not be mapped to the Ballerina headers.", DiagnosticSeverity.ERROR), OAS_SERVICE_107("OAS_SERVICE_107", "HTTP status code '%s' is not supported in Ballerina.", - DiagnosticSeverity.ERROR); + DiagnosticSeverity.ERROR); private final String code; private final String description; @@ -60,14 +62,17 @@ public enum ServiceDiagnosticMessages { } public String getCode() { + return code; } public String getDescription() { + return description; } public DiagnosticSeverity getSeverity() { + return severity; } } diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceGenerationUtils.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceGenerationUtils.java new file mode 100644 index 000000000..501028a91 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/ServiceGenerationUtils.java @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service; + +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.BasicLiteralNode; +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.MetadataNode; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +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.UnionTypeDescriptorNode; +import io.ballerina.openapi.core.GeneratorConstants; +import io.ballerina.openapi.core.GeneratorUtils; +import io.ballerina.openapi.core.exception.BallerinaOpenApiException; +import io.ballerina.openapi.core.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyMinutiaeList; +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.createAnnotationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBasicLiteralNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +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.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSpecificFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +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.STRING_LITERAL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD; +import static io.ballerina.openapi.core.GeneratorConstants.BOOLEAN; +import static io.ballerina.openapi.core.GeneratorConstants.INTEGER; +import static io.ballerina.openapi.core.GeneratorConstants.JSON; +import static io.ballerina.openapi.core.GeneratorConstants.NUMBER; +import static io.ballerina.openapi.core.GeneratorConstants.STRING; + +/** + * This store all the util functions related service generation process. + * + * @since 1.3.0 + */ +public class ServiceGenerationUtils { + + /** + * This method will extract reference type by splitting the reference string. + * + * @param referenceVariable - Reference String + * @return Reference variable name + * @throws BallerinaOpenApiException - 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 BallerinaOpenApiException { + + if (referenceVariable.startsWith("#") && referenceVariable.contains("/")) { + String[] refArray = referenceVariable.split("/"); + return GeneratorUtils.escapeIdentifier(refArray[refArray.length - 1]); + } else { + throw new BallerinaOpenApiException("Invalid reference value : " + referenceVariable + + "\nBallerina only supports local reference values."); + } + } + + public static AnnotationNode getAnnotationNode(String identifier, MappingConstructorExpressionNode annotValue) { + + Token atToken = createIdentifierToken("@"); + QualifiedNameReferenceNode annotReference = GeneratorUtils.getQualifiedNameReferenceNode( + GeneratorConstants.HTTP, identifier); + return createAnnotationNode(atToken, annotReference, annotValue); + } + + public static UnionTypeDescriptorNode getUnionNodeForOneOf(Iterator iterator) + throws BallerinaOpenApiException { + + List qualifiedNodes = new ArrayList<>(); + Token pipeToken = createIdentifierToken("|"); + while (iterator.hasNext()) { + Schema contentType = iterator.next(); + Optional qualifiedNodeType = generateTypeDescNodeForOASSchema(contentType); + if (qualifiedNodeType.isEmpty()) { + continue; + } + qualifiedNodes.add((SimpleNameReferenceNode) qualifiedNodeType.get()); + } + SimpleNameReferenceNode right = qualifiedNodes.get(qualifiedNodes.size() - 1); + SimpleNameReferenceNode traversRight = qualifiedNodes.get(qualifiedNodes.size() - 2); + UnionTypeDescriptorNode traversUnion = createUnionTypeDescriptorNode(traversRight, pipeToken, + right); + if (qualifiedNodes.size() >= 3) { + for (int i = qualifiedNodes.size() - 3; i >= 0; i--) { + traversUnion = createUnionTypeDescriptorNode(qualifiedNodes.get(i), pipeToken, + traversUnion); + } + } + return traversUnion; + } + + /** + * Generate typeDescriptor for given schema. + */ + public static Optional generateTypeDescNodeForOASSchema(Schema schema) + throws BallerinaOpenApiException { + if (schema == null) { + return Optional.empty(); + } + + if (schema.get$ref() != null) { + String schemaName = GeneratorUtils.getValidName(extractReferenceType(schema.get$ref()), true); + return Optional.ofNullable(createSimpleNameReferenceNode(createIdentifierToken(schemaName))); + } else if (GeneratorUtils.isMapSchema(schema)) { + RecordTypeGenerator recordTypeGenerator = new RecordTypeGenerator(schema, null); + TypeDescriptorNode record = recordTypeGenerator.generateTypeDescriptorNode(); + return Optional.ofNullable(record); + } else if (GeneratorUtils.getOpenAPIType(schema) != null) { + String schemaType = GeneratorUtils.getOpenAPIType(schema); + boolean isPrimitiveType = schemaType.equals(INTEGER) || schemaType.equals(NUMBER) || + schemaType.equals(BOOLEAN) || schemaType.equals(STRING); + if (GeneratorUtils.isArraySchema(schema)) { + return getTypeDescNodeForArraySchema(schema); + } else if (isPrimitiveType) { + //This returns identifier node for the types: int, float, decimal, boolean, string + IdentifierToken identifierToken = createIdentifierToken( + GeneratorUtils.convertOpenAPITypeToBallerina(schema), + AbstractNodeFactory.createEmptyMinutiaeList(), GeneratorUtils.SINGLE_WS_MINUTIAE); + return Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)); + } else { + return Optional.empty(); + } + } else if (schema.getOneOf() != null) { + Iterator iterator = schema.getOneOf().iterator(); + return Optional.ofNullable(getUnionNodeForOneOf(iterator)); + } else { + return Optional.empty(); + } + } + + /** + * Generate {@code TypeDescriptorNode} for ArraySchema in OAS. + */ + private static Optional getTypeDescNodeForArraySchema(Schema schema) + throws BallerinaOpenApiException { + TypeDescriptorNode member; + String schemaType = GeneratorUtils.getOpenAPIType(schema.getItems()); + if (schema.getItems().get$ref() != null) { + member = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(GeneratorUtils.getValidName( + extractReferenceType(schema.getItems().get$ref()), true))); + } else if (schemaType != null && (schemaType.equals(INTEGER) || schemaType.equals(NUMBER) || + schemaType.equals(BOOLEAN) || schemaType.equals(STRING))) { + member = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken( + GeneratorUtils.convertOpenAPITypeToBallerina(schema.getItems()))); + } else { + return Optional.empty(); + } + ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + NodeList nodeList = createNodeList(dimensionNode); + return Optional.ofNullable(createArrayTypeDescriptorNode(member, nodeList)); + } + + /** + * Generate TypeDescriptor for all the mediaTypes. + * + * Here return the @code{ImmutablePair, TypeDefinitionNode>} for return type. + * Left node(key) of the return tuple represents the return type node for given mediaType details, Right Node + * (Value) of the return tuple represents the newly generated TypeDefinitionNode for return type if it has inline + * objects. + */ + + public static ImmutablePair, Optional> handleMediaType( + Map.Entry mediaType, String recordName) throws BallerinaOpenApiException { + String mediaTypeContent = selectMediaType(mediaType.getKey().trim()); + + MediaType value = mediaType.getValue(); + Schema schema = value.getSchema(); + IdentifierToken identifierToken; + switch (mediaTypeContent) { + case GeneratorConstants.APPLICATION_JSON: + Optional returnTypeDecNode = generateTypeDescNodeForOASSchema(schema); + if (returnTypeDecNode.isEmpty()) { + return ImmutablePair.of(Optional.ofNullable(createSimpleNameReferenceNode(createIdentifierToken( + JSON))), Optional.empty()); + } else if (returnTypeDecNode.get() instanceof RecordTypeDescriptorNode) { + RecordTypeDescriptorNode recordNode = (RecordTypeDescriptorNode) returnTypeDecNode.get(); + if (recordName == null) { + return ImmutablePair.of(returnTypeDecNode, Optional.empty()); + } + TypeDefinitionNode typeDefinitionNode = createTypeDefinitionNode(null, + createToken(PUBLIC_KEYWORD), + createToken(TYPE_KEYWORD), + createIdentifierToken(recordName), + recordNode, + createToken(SEMICOLON_TOKEN)); + return ImmutablePair.of(returnTypeDecNode, Optional.of(typeDefinitionNode)); + } else { + return ImmutablePair.of(returnTypeDecNode, Optional.empty()); + } + case GeneratorConstants.APPLICATION_XML: + identifierToken = createIdentifierToken(GeneratorConstants.XML); + return ImmutablePair.of(Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)), + Optional.empty()); + case GeneratorConstants.APPLICATION_URL_ENCODE: + identifierToken = createIdentifierToken(GeneratorConstants.MAP_STRING); + return ImmutablePair.of(Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)), + Optional.empty()); + case GeneratorConstants.TEXT: + identifierToken = createIdentifierToken(GeneratorConstants.STRING); + return ImmutablePair.of(Optional.ofNullable(createSimpleNameReferenceNode(identifierToken)), + Optional.empty()); + case GeneratorConstants.APPLICATION_OCTET_STREAM: + ArrayDimensionNode dimensionNode = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + return ImmutablePair.of(Optional.ofNullable( + createArrayTypeDescriptorNode(createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(GeneratorConstants.BYTE)), + NodeFactory.createNodeList(dimensionNode))), Optional.empty()); + default: + return ImmutablePair.of(Optional.empty(), Optional.empty()); + } + } + + /** + * + * This util is used for selecting standard media type by looking at the user defined media type. + */ + public static String selectMediaType(String mediaTypeContent) { + + if (mediaTypeContent.matches("application/.*\\+json") || mediaTypeContent.matches(".*/json")) { + mediaTypeContent = GeneratorConstants.APPLICATION_JSON; + } else if (mediaTypeContent.matches("application/.*\\+xml") || mediaTypeContent.matches(".*/xml")) { + mediaTypeContent = GeneratorConstants.APPLICATION_XML; + } else if (mediaTypeContent.matches("text/.*")) { + mediaTypeContent = GeneratorConstants.TEXT; + } else if (mediaTypeContent.matches("application/.*\\+octet-stream")) { + mediaTypeContent = GeneratorConstants.APPLICATION_OCTET_STREAM; + } else if (mediaTypeContent.matches("application/.*\\+x-www-form-urlencoded")) { + mediaTypeContent = GeneratorConstants.APPLICATION_URL_ENCODE; + } + return mediaTypeContent; + } + + /** + * This util function is for generating service config annotation. + *
+     *     @http:ServiceConfig {
+     *          treatNilableAsOptional : false
+     *      }
+     * 
+ */ + public static MetadataNode generateServiceConfigAnnotation() { + MetadataNode metadataNode; + BasicLiteralNode valueExpr = createBasicLiteralNode(STRING_LITERAL, + createLiteralValueToken(SyntaxKind.STRING_LITERAL_TOKEN, GeneratorConstants.FALSE, + createEmptyMinutiaeList(), + createEmptyMinutiaeList())); + SpecificFieldNode fields = createSpecificFieldNode(null, + createIdentifierToken( + GeneratorConstants.TREAT_NILABLE_AS_OPTIONAL), createToken(COLON_TOKEN), valueExpr); + AnnotationNode annotationNode = createAnnotationNode(createToken(SyntaxKind.AT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken( + GeneratorConstants.SERVICE_CONFIG, GeneratorUtils.SINGLE_WS_MINUTIAE, + GeneratorUtils.SINGLE_WS_MINUTIAE)), createMappingConstructorExpressionNode( + createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(fields), + createToken(CLOSE_BRACE_TOKEN))); + metadataNode = createMetadataNode(null, createSeparatedNodeList(annotationNode)); + return metadataNode; + } + + /** + * This util function is for generating the import node for http module. + */ + public static NodeList createImportDeclarationNodes() { + List imports = new ArrayList<>(); + ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA + , GeneratorConstants.HTTP); + imports.add(importForHttp); + return AbstractNodeFactory.createNodeList(imports); + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/model/OASServiceMetadata.java b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/model/OASServiceMetadata.java new file mode 100644 index 000000000..cdf6c1630 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/generators/service/model/OASServiceMetadata.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.generators.service.model; + +import io.ballerina.openapi.core.model.Filter; +import io.swagger.v3.oas.models.OpenAPI; + +/** + * This class stores metadata that related to service code generations. + * + * @since 1.4.0 + */ +public class OASServiceMetadata { + + private final OpenAPI openAPI; + private final Filter filters; + private final boolean nullable; + private final boolean generateServiceType; + private final boolean generateWithoutDataBinding; + + private OASServiceMetadata(Builder serviceMetadataBuilder) { + this.openAPI = serviceMetadataBuilder.openAPI; + this.filters = serviceMetadataBuilder.filters; + this.nullable = serviceMetadataBuilder.nullable; + this.generateServiceType = serviceMetadataBuilder.generateServiceType; + this.generateWithoutDataBinding = serviceMetadataBuilder.generateWithoutDataBinding; + } + + public OpenAPI getOpenAPI() { + return openAPI; + } + + public Filter getFilters() { + return filters; + } + + public boolean isNullable() { + return nullable; + } + + public boolean isServiceTypeRequired() { + return generateServiceType; + } + + public boolean generateWithoutDataBinding() { + return generateWithoutDataBinding; + } + + /** + * Service generation meta data builder class. + */ + public static class Builder { + + private OpenAPI openAPI; + private Filter filters; + private boolean nullable = false; + + private boolean generateServiceType = false; + + private boolean generateWithoutDataBinding = false; + + public Builder withOpenAPI(OpenAPI openAPI) { + this.openAPI = openAPI; + return this; + } + + public Builder withFilters(Filter filters) { + this.filters = filters; + return this; + } + + public Builder withNullable(boolean nullable) { + this.nullable = nullable; + return this; + } + + public Builder withGenerateServiceType(boolean generateServiceType) { + this.generateServiceType = generateServiceType; + return this; + } + + public Builder withGenerateWithoutDataBinding(boolean generateWithoutDataBinding) { + this.generateWithoutDataBinding = generateWithoutDataBinding; + return this; + } + + public OASServiceMetadata build() { + return new OASServiceMetadata(this); + } + } +} diff --git a/openapi-core/src/main/java/io/ballerina/openapi/core/model/Filter.java b/openapi-core/src/main/java/io/ballerina/openapi/core/model/Filter.java new file mode 100644 index 000000000..1fdf05780 --- /dev/null +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/model/Filter.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.core.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * This model use for storing the filter tags and operations details. + * + * @since 1.3.0 + */ +public class Filter { + private List tags = new ArrayList<>(); + private List operations = new ArrayList<>(); + + public Filter() { + } + public Filter(List tags, List operations) { + this.tags = tags; + this.operations = operations; + } + + public List getTags() { + return tags; + } + + public List getOperations() { + return operations; + } + + public void setOperations(List operations) { + this.operations = operations; + } + + public void setTags(List tags) { + this.tags = tags; + } +} diff --git a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/model/GenSrcFile.java b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java similarity index 65% rename from openapi-cli/src/main/java/io/ballerina/openapi/cmd/model/GenSrcFile.java rename to openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java index 591700fb6..55d4463e2 100644 --- a/openapi-cli/src/main/java/io/ballerina/openapi/cmd/model/GenSrcFile.java +++ b/openapi-core/src/main/java/io/ballerina/openapi/core/model/GenSrcFile.java @@ -1,23 +1,27 @@ /* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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 + * 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. + * 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.openapi.cmd.model; +package io.ballerina.openapi.core.model; /** * Model class to hold generated source file information. + * + * @since 1.3.0 */ public class GenSrcFile { private String content; @@ -33,10 +37,12 @@ public enum GenFileType { MODEL_SRC, IMPL_SRC, TEST_SRC, - RES; + CONFIG_SRC, + RES, + UTIL_SRC; public boolean isOverwritable() { - if (this == GEN_SRC || this == RES || this == MODEL_SRC) { + if (this == GEN_SRC || this == RES || this == MODEL_SRC || this == UTIL_SRC) { return true; } diff --git a/openapi-core/src/main/java/module-info.java b/openapi-core/src/main/java/module-info.java new file mode 100644 index 000000000..09f9f0ecc --- /dev/null +++ b/openapi-core/src/main/java/module-info.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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. + */ + +module io.ballerina.openapi.core { + requires handlebars; + requires info.picocli; + requires io.ballerina.lang; + requires io.ballerina.parser; + requires io.ballerina.stdlib.http; + requires io.ballerina.cli; + requires io.ballerina.tools.api; + requires io.ballerina.runtime; + requires io.ballerina.formatter.core; + requires io.ballerina.openapi.converter; + requires io.swagger.v3.core; + requires io.swagger.v3.oas.models; + requires java.ws.rs; + requires jsr305; + requires org.apache.commons.io; + requires org.slf4j; + requires swagger.parser; + requires swagger.parser.core; + requires swagger.parser.v3; + requires org.apache.commons.lang3; + + exports io.ballerina.openapi.core.generators.service; + exports io.ballerina.openapi.core.model; + exports io.ballerina.openapi.core.exception; + exports io.ballerina.openapi.core.generators.client; + exports io.ballerina.openapi.core.generators.schema; + exports io.ballerina.openapi.core; + exports io.ballerina.openapi.core.generators.client.model; + exports io.ballerina.openapi.core.generators.service.model; +} + diff --git a/openapi-cli/src/main/resources/config_toml_files/api_key_config.toml b/openapi-core/src/main/resources/config_toml_files/api_key_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/api_key_config.toml rename to openapi-core/src/main/resources/config_toml_files/api_key_config.toml diff --git a/openapi-cli/src/main/resources/config_toml_files/basic_config.toml b/openapi-core/src/main/resources/config_toml_files/basic_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/basic_config.toml rename to openapi-core/src/main/resources/config_toml_files/basic_config.toml diff --git a/openapi-cli/src/main/resources/config_toml_files/bearer_config.toml b/openapi-core/src/main/resources/config_toml_files/bearer_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/bearer_config.toml rename to openapi-core/src/main/resources/config_toml_files/bearer_config.toml diff --git a/openapi-cli/src/main/resources/config_toml_files/client_credentials_config.toml b/openapi-core/src/main/resources/config_toml_files/client_credentials_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/client_credentials_config.toml rename to openapi-core/src/main/resources/config_toml_files/client_credentials_config.toml diff --git a/openapi-cli/src/main/resources/config_toml_files/password_config.toml b/openapi-core/src/main/resources/config_toml_files/password_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/password_config.toml rename to openapi-core/src/main/resources/config_toml_files/password_config.toml diff --git a/openapi-cli/src/main/resources/config_toml_files/refresh_token_config.toml b/openapi-core/src/main/resources/config_toml_files/refresh_token_config.toml similarity index 100% rename from openapi-cli/src/main/resources/config_toml_files/refresh_token_config.toml rename to openapi-core/src/main/resources/config_toml_files/refresh_token_config.toml diff --git a/openapi-cli/src/main/resources/templates/utils_openapi.bal b/openapi-core/src/main/resources/templates/utils_openapi.bal similarity index 92% rename from openapi-cli/src/main/resources/templates/utils_openapi.bal rename to openapi-core/src/main/resources/templates/utils_openapi.bal index 49b0d2a12..d1a1c6a66 100644 --- a/openapi-cli/src/main/resources/templates/utils_openapi.bal +++ b/openapi-core/src/main/resources/templates/utils_openapi.bal @@ -251,17 +251,22 @@ isolated function getMapForHeaders(map headerParam) returns map encodingMap = {}) -returns mime:Entity[]|error { +isolated function createBodyParts(record {|anydata...;|} anyRecord, map encodingMap = {}) returns mime:Entity[]|error { mime:Entity[] entities = []; foreach [string, anydata] [key, value] in anyRecord.entries() { - Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : {}; + Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : {}; mime:Entity entity = new mime:Entity(); - if value is byte[] { + if value is record {byte[] fileContent; string fileName;} { + entity.setContentDisposition(mime:getContentDispositionObject(string `form-data; name=${key}; filename=${value.fileName}`)); + entity.setByteArray(value.fileContent); + } else if value is byte[] { + entity.setContentDisposition(mime:getContentDispositionObject(string `form-data; name=${key};`)); entity.setByteArray(value); } else if value is SimpleBasicType|SimpleBasicType[] { + entity.setContentDisposition(mime:getContentDispositionObject(string `form-data; name=${key};`)); entity.setText(value.toString()); } else if value is record {}|record {}[] { + entity.setContentDisposition(mime:getContentDispositionObject(string `form-data; name=${key};`)); entity.setJson(value.toJson()); } if (encodingData?.contentType is string) { diff --git a/openapi-extension-tests/build.gradle b/openapi-extension-tests/build.gradle index 2adaff685..7e5ee134f 100644 --- a/openapi-extension-tests/build.gradle +++ b/openapi-extension-tests/build.gradle @@ -33,9 +33,9 @@ dependencies { testImplementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}" testImplementation group: 'org.ballerinalang', name: 'ballerina-tools-api', version: "${ballerinaLangVersion}" testImplementation group: 'org.ballerinalang', name: 'ballerina-parser', version: "${ballerinaLangVersion}" - testRuntime group: 'commons-io', name: 'commons-io', version: "${commonsIoVersion}" - testRuntime project(':openapi-bal-service') - testRuntime project(':openapi-extension') + testRuntimeOnly group: 'commons-io', name: 'commons-io', version: "${commonsIoVersion}" + testRuntimeOnly project(':openapi-bal-service') + testRuntimeOnly project(':openapi-extension') testImplementation group: 'org.testng', name: 'testng', version: "${testngVersion}" } @@ -81,9 +81,9 @@ jacocoTestReport { def classFiles = new File("${rootDir}/openapi-extension/build/classes/java/main/io/ballerina/openapi/extension") additionalClassDirs(classFiles) reports { - xml.enabled = true - html.enabled = true - csv.enabled = true + xml.required = true + html.required = true + csv.required = true xml.destination = new File("${buildDir}/reports/jacoco/report.xml") html.destination = new File("${buildDir}/reports/jacoco/report.html") csv.destination = new File("${buildDir}/reports/jacoco/report.csv") @@ -91,3 +91,5 @@ jacocoTestReport { } copyPackageBala.dependsOn copyDistribution test.dependsOn copyPackageBala +copyDistribution.dependsOn(':module-ballerina-openapi:unpackJballerinaTools') +copyDistribution.dependsOn(':module-ballerina-openapi:copyStdlibs') diff --git a/openapi-extension/build.gradle b/openapi-extension/build.gradle index 409749337..ccb11df30 100644 --- a/openapi-extension/build.gradle +++ b/openapi-extension/build.gradle @@ -15,11 +15,14 @@ * */ +apply from: "$rootDir/gradle/javaProject.gradle" description = 'Ballerina - OpenAPI Extension' -apply plugin: "java" +apply plugin: "java-library" dependencies { + implementation "io.swagger.core.v3:swagger-core" + implementation "io.swagger.core.v3:swagger-models" implementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}" implementation group: 'org.ballerinalang', name: 'ballerina-tools-api', version: "${ballerinaLangVersion}" implementation group: 'org.ballerinalang', name: 'ballerina-parser', version: "${ballerinaLangVersion}" diff --git a/openapi-extension/src/main/java/io/ballerina/openapi/extension/context/OpenApiDocContextHandler.java b/openapi-extension/src/main/java/io/ballerina/openapi/extension/context/OpenApiDocContextHandler.java index d8e1c6639..2667c3eb1 100644 --- a/openapi-extension/src/main/java/io/ballerina/openapi/extension/context/OpenApiDocContextHandler.java +++ b/openapi-extension/src/main/java/io/ballerina/openapi/extension/context/OpenApiDocContextHandler.java @@ -29,7 +29,7 @@ * {@code OpenApiDocContextHandler} will manage the shared context among compiler plugin tasks. */ public final class OpenApiDocContextHandler { - private static OpenApiDocContextHandler INSTANCE; + private static OpenApiDocContextHandler instance; private final List contexts; @@ -39,11 +39,11 @@ private OpenApiDocContextHandler() { public static OpenApiDocContextHandler getContextHandler() { synchronized (OpenApiDocContextHandler.class) { - if (Objects.isNull(INSTANCE)) { - INSTANCE = new OpenApiDocContextHandler(); + if (Objects.isNull(instance)) { + instance = new OpenApiDocContextHandler(); } } - return INSTANCE; + return instance; } public void addContext(OpenApiDocContext context) { diff --git a/openapi-extension/src/main/java/io/ballerina/openapi/extension/doc/gen/AbstractOpenApiDocGenerator.java b/openapi-extension/src/main/java/io/ballerina/openapi/extension/doc/gen/AbstractOpenApiDocGenerator.java index f7c64a0ab..b2bd3a515 100644 --- a/openapi-extension/src/main/java/io/ballerina/openapi/extension/doc/gen/AbstractOpenApiDocGenerator.java +++ b/openapi-extension/src/main/java/io/ballerina/openapi/extension/doc/gen/AbstractOpenApiDocGenerator.java @@ -16,32 +16,33 @@ package io.ballerina.openapi.extension.doc.gen; -import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.syntax.tree.AnnotationNode; -import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; import io.ballerina.compiler.syntax.tree.MetadataNode; -import io.ballerina.compiler.syntax.tree.ModulePartNode; import io.ballerina.compiler.syntax.tree.NodeList; import io.ballerina.compiler.syntax.tree.NodeLocation; 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.openapi.converter.model.OASGenerationMetaInfo; +import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; import io.ballerina.openapi.extension.Constants; import io.ballerina.openapi.extension.OpenApiDiagnosticCode; import io.ballerina.openapi.extension.context.OpenApiDocContext; import io.ballerina.projects.Package; +import io.ballerina.projects.Project; import io.ballerina.projects.plugins.SyntaxNodeAnalysisContext; import io.ballerina.tools.diagnostics.Diagnostic; +import io.swagger.v3.core.util.Json; +import io.swagger.v3.oas.models.OpenAPI; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; +import static io.ballerina.openapi.converter.Constants.SLASH; +import static io.ballerina.openapi.converter.utils.ConverterCommonUtils.normalizeTitle; import static io.ballerina.openapi.extension.context.OpenApiDocContextHandler.getContextHandler; import static io.ballerina.openapi.extension.doc.DocGenerationUtils.getDiagnostics; @@ -49,6 +50,8 @@ * {@code AbstractOpenApiDocGenerator} contains the basic utilities required for OpenAPI doc generation. */ public abstract class AbstractOpenApiDocGenerator implements OpenApiDocGenerator { + private static final String FILE_NAME_FORMAT = "%d.json"; + private final OpenApiContractResolver contractResolver; public AbstractOpenApiDocGenerator() { @@ -67,7 +70,6 @@ public void generate(OpenApiDocConfig config, SyntaxNodeAnalysisContext context, ServiceDeclarationNode serviceNode = config.getServiceNode(); Optional serviceInfoAnnotationOpt = getServiceInfoAnnotation(serviceNode); - String targetFile = String.format("%d.json", serviceId); if (serviceInfoAnnotationOpt.isPresent()) { AnnotationNode serviceInfoAnnotation = serviceInfoAnnotationOpt.get(); @@ -88,27 +90,10 @@ public void generate(OpenApiDocConfig config, SyntaxNodeAnalysisContext context, updateOpenApiContext(context, serviceId, openApiDefinition, embed); } else { // generate open-api doc and update the context if the `contract` configuration is not available - String openApiDefinition = generateOpenApiDoc( - config.getSemanticModel(), config.getSyntaxTree(), serviceNode, targetFile); - if (null != openApiDefinition && !openApiDefinition.isBlank()) { - updateOpenApiContext(context, serviceId, openApiDefinition, embed); - } else { - OpenApiDiagnosticCode errorCode = OpenApiDiagnosticCode.OPENAPI_107; - updateCompilerContext(context, location, errorCode); - } - } - } else { - // generate open-api doc and update the context - String openApiDefinition = generateOpenApiDoc( - config.getSemanticModel(), config.getSyntaxTree(), serviceNode, targetFile); - if (null != openApiDefinition && !openApiDefinition.isBlank()) { - updateOpenApiContext(context, serviceId, openApiDefinition, false); - } else { - OpenApiDiagnosticCode errorCode = OpenApiDiagnosticCode.OPENAPI_107; - updateCompilerContext(context, location, errorCode); + generateOpenApiDoc(currentPackage.project(), config, context, location, embed); } } - } catch (Exception e) { + } catch (IOException | RuntimeException e) { // currently, we do not have open-api doc generation logic for following scenarios: // 1. default resources and for scenarios // 2. returning http-response from a resource @@ -157,19 +142,33 @@ private Optional retrieveValueForAnnotationFields(AnnotationNode service .map(en -> en.toString().trim()); } - private String generateOpenApiDoc(SemanticModel semanticModel, SyntaxTree syntaxTree, - ServiceDeclarationNode serviceNode, String outputFileName) { - ModulePartNode modulePartNode = syntaxTree.rootNode(); - List listenerNodes = extractListenerNodes(modulePartNode); - return ServiceToOpenAPIConverterUtils.generateOASForGivenFormat(serviceNode, true, listenerNodes, - semanticModel, outputFileName); - } - - private List extractListenerNodes(ModulePartNode modulePartNode) { - return modulePartNode.members().stream() - .filter(n -> SyntaxKind.LISTENER_DECLARATION.equals(n.kind())) - .map(n -> (ListenerDeclarationNode) n) - .collect(Collectors.toList()); + private void generateOpenApiDoc(Project project, OpenApiDocConfig config, SyntaxNodeAnalysisContext context, + NodeLocation location, boolean embed) { + if (!embed) { + return; + } + int serviceId = config.getSemanticModel().hashCode(); + String targetFile = String.format(FILE_NAME_FORMAT, serviceId); + OASGenerationMetaInfo.OASGenerationMetaInfoBuilder builder = new + OASGenerationMetaInfo.OASGenerationMetaInfoBuilder(); + builder.setServiceDeclarationNode(config.getServiceNode()) + .setSemanticModel(config.getSemanticModel()) + .setOpenApiFileName(targetFile) + .setBallerinaFilePath(null) + .setProject(project); + OASResult oasResult = ServiceToOpenAPIConverterUtils.generateOAS(builder.build()); + Optional openApiOpt = oasResult.getOpenAPI(); + if (!oasResult.getDiagnostics().isEmpty() || openApiOpt.isEmpty()) { + OpenApiDiagnosticCode errorCode = OpenApiDiagnosticCode.OPENAPI_107; + updateCompilerContext(context, location, errorCode); + return; + } + OpenAPI openApi = openApiOpt.get(); + if (openApi.getInfo().getTitle() == null || openApi.getInfo().getTitle().equals(SLASH)) { + openApi.getInfo().setTitle(normalizeTitle(targetFile)); + } + String openApiDefinition = Json.pretty(openApi); + updateOpenApiContext(context, serviceId, openApiDefinition, embed); } protected Path retrieveProjectRoot(Path projectRoot) { diff --git a/openapi-extension/src/main/java/module-info.java b/openapi-extension/src/main/java/module-info.java index e7687ea97..1ce54dcf1 100644 --- a/openapi-extension/src/main/java/module-info.java +++ b/openapi-extension/src/main/java/module-info.java @@ -15,6 +15,8 @@ */ module ballerina.openapi.extension { + requires io.swagger.v3.core; + requires io.swagger.v3.oas.models; requires io.ballerina.lang; requires io.ballerina.tools.api; requires io.ballerina.parser; diff --git a/openapi-integration-tests/build.gradle b/openapi-integration-tests/build.gradle index bdabe720b..f274a3452 100644 --- a/openapi-integration-tests/build.gradle +++ b/openapi-integration-tests/build.gradle @@ -74,8 +74,8 @@ task copyOpenAPI() { test { systemProperties = [ jacocoAgentLine: "-javaagent:${configurations.jacocoRuntime.asPath}=destfile=${test.jacoco.destinationFile.absolutePath},append=true,inclnolocationclasses=true,exclclassloader=jdk.internal.reflect.DelegatingClassLoader" , - "distributions.dir": bDistribution, - "target.dir": "$project.buildDir" + "distributions.dir": bDistribution, + "target.dir": "$project.buildDir" ] useTestNG() { @@ -95,9 +95,9 @@ jacocoTestReport { additionalClassDirs(validatorClassFiles) additionalClassDirs(buildClassFiles) reports { - xml.enabled = true - html.enabled = true - csv.enabled = true + xml.required = true + html.required = true + csv.required = true xml.destination = new File("${buildDir}/reports/jacoco/report.xml") html.destination = new File("${buildDir}/reports/jacoco/report.html") csv.destination = new File("${buildDir}/reports/jacoco/report.csv") diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/OpenAPITest.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/OpenAPITest.java index 4f62a3194..29740d0d1 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/OpenAPITest.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/OpenAPITest.java @@ -17,7 +17,6 @@ */ package io.ballerina.openapi; -import io.ballerina.openapi.cmd.TestUtil; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; @@ -90,8 +89,7 @@ private static String getStringFromGivenBalFile(Path expectedServiceFile) throws } public void compareGeneratedSyntaxTreewithExpectedSyntaxTree(String generated, String balfile) throws IOException { - String expectedBallerinaContent = getStringFromGivenBalFile(RES_DIR.resolve( - "service/return/ballerina").resolve(balfile)); + String expectedBallerinaContent = getStringFromGivenBalFile(RES_DIR.resolve(balfile)); String generatedFile = getStringFromGivenBalFile(this.tmpDir.resolve(generated)); generatedFile = (generatedFile.trim()).replaceAll("\\s+", ""); expectedBallerinaContent = (expectedBallerinaContent.trim()).replaceAll("\\s+", ""); diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/TestUtil.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/TestUtil.java similarity index 69% rename from openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/TestUtil.java rename to openapi-integration-tests/src/test/java/io/ballerina/openapi/TestUtil.java index 11529fb72..200c69b9a 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/TestUtil.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/TestUtil.java @@ -16,13 +16,15 @@ * under the License. */ -package io.ballerina.openapi.cmd; +package io.ballerina.openapi; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; +import org.testng.Assert; import java.io.BufferedReader; import java.io.File; +import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -31,8 +33,15 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.openapi.extension.build.ValidatorTests.WHITESPACE_PATTERN; +import static io.ballerina.openapi.idl.client.IDLClientGenPluginTests.DISTRIBUTION_FILE_NAME; +import static io.ballerina.openapi.idl.client.IDLClientGenPluginTests.TEST_RESOURCE; /** * This class for storing the test utils for integration tests. @@ -43,7 +52,7 @@ public class TestUtil { public static final Path DISTRIBUTIONS_DIR = Paths.get(System.getProperty("distributions.dir")); public static final Path TEST_DISTRIBUTION_PATH = TARGET_DIR.resolve("test-distribution"); public static final Path RESOURCES_PATH = TARGET_DIR.resolve("resources/test"); - public static final Path RESOURCE = Paths.get(System.getProperty("user.dir")).resolve("build/resources/test/build"); + public static final Path RESOURCE = Paths.get(System.getProperty("user.dir")).resolve("build/resources/test"); private static String balFile = "bal"; /** @@ -75,6 +84,13 @@ public static InputStream executeOpenapiBuild(String distributionName, Path sour return process.getErrorStream(); } + public static InputStream executeOpenAPIToTestWarnings(String distributionName, Path sourceDirectory, + List args) throws IOException { + args.add(0, "openapi"); + Process process = getProcessBuilderResults(distributionName, sourceDirectory, args); + return process.getErrorStream(); + } + /** * Ballerina build command. */ @@ -88,6 +104,16 @@ public static boolean executeBuild(String distributionName, Path sourceDirectory return exitCode == 0; } + /** + * Ballerina run command. + */ + public static Process executeRun(String distributionName, Path sourceDirectory, + List args) throws IOException, InterruptedException { + args.add(0, "run"); + Process process = getProcessBuilderResults(distributionName, sourceDirectory, args); + int exitCode = process.waitFor(); + return process; + } /** * Execute ballerina openapi command. * @@ -126,8 +152,7 @@ public static Process getProcessBuilderResults(String distributionName, Path sou OUT.println("Executing: " + StringUtils.join(args, ' ')); ProcessBuilder pb = new ProcessBuilder(args); pb.directory(sourceDirectory.toFile()); - Process process = pb.start(); - return process; + return pb.start(); } /** @@ -163,4 +188,36 @@ public static void deleteGeneratedFiles(String generatedFileName) throws IOExcep } } } + + public static File[] getMatchingFiles(String project, List ids) throws IOException, InterruptedException { + List buildArgs = new LinkedList<>(); + //TODO: Change this function after fixing module name with client declaration alias. + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve(project), buildArgs); + Assert.assertEquals(process.waitFor(), 0); + File dir = new File(RESOURCE.resolve("client-idl-projects/" + project + "/generated/").toString()); + File[] matchingFiles = dir.listFiles(new FileFilter() { + public boolean accept(File pathname) { + for (String id : ids) { + if (pathname.getName().contains(id)) { + return true; + } + } + return false; + } + }); + return matchingFiles; + } + + public static void assertOnErrorStream(Process process, String msg) throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + Stream logLines = br.lines(); + String generatedLog = logLines.collect(Collectors.joining("\n")); + logLines.close(); + String formattedGeneratedLog = (generatedLog.trim()).replaceAll(WHITESPACE_PATTERN, ""); + String formattedMessage = msg.trim().replaceAll(WHITESPACE_PATTERN, ""); + Assert.assertTrue(formattedGeneratedLog.contains(formattedMessage), + String.format("compiler output doesn't contain the expected" + + " output: %s : generated output : %s", msg, generatedLog)); + } + } } diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/BallerinaToOpenAPITests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/BallerinaToOpenAPITests.java index 37a3bcfe5..dd7047a1f 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/BallerinaToOpenAPITests.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/BallerinaToOpenAPITests.java @@ -17,6 +17,7 @@ */ package io.ballerina.openapi.cmd; +import io.ballerina.openapi.TestUtil; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -33,8 +34,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static io.ballerina.openapi.cmd.TestUtil.DISTRIBUTIONS_DIR; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; /** * This {@code BallerinaToOpenAPITests} contains all the ballerina to openapi command with compiler annotation. @@ -124,6 +125,25 @@ public void nonHttpService() throws IOException, InterruptedException { Assert.assertFalse(Files.exists(TEST_RESOURCE.resolve("query_openapi.yaml"))); } + @Test(description = "Service is with non openapi annotation") + public void nonOpenAPIAnnotation() throws IOException, InterruptedException { + executeCommand("project_non_openapi_annotation/service.bal", "service_openapi.yaml", + "project_non_openapi_annotation/result.yaml"); + } + + @Test(description = "Service is with non openapi annotation and slash as base path") + public void nonOpenAPIAnnotationWithSlash() throws IOException, InterruptedException { + executeCommand("project_non_openapi_annotation_with_base_path/service.bal", "payload_openapi.yaml", + "project_non_openapi_annotation_with_base_path/result.yaml"); + } + + @Test(description = "Service is with non openapi annotation and without a base path") + public void nonOpenAPIAnnotationWithWithoutBasePath() throws IOException, InterruptedException { + executeCommand("project_non_openapi_annotation_without_base_path/service_file.bal", + "service_file_openapi.yaml", + "project_non_openapi_annotation_without_base_path/result.yaml"); + } + @AfterClass public void cleanUp() throws IOException { TestUtil.cleanDistribution(); diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ClientGenerationTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ClientGenerationTests.java index 3a8ed1ebc..b4ef3d9ef 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ClientGenerationTests.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ClientGenerationTests.java @@ -18,6 +18,7 @@ package io.ballerina.openapi.cmd; import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; import org.testng.Assert; import org.testng.annotations.Test; @@ -28,8 +29,8 @@ import java.util.LinkedList; import java.util.List; -import static io.ballerina.openapi.cmd.TestUtil.DISTRIBUTIONS_DIR; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; /** * Integration tests for client resource functions. diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationNegativeTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationNegativeTests.java new file mode 100644 index 000000000..9134a57f0 --- /dev/null +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationNegativeTests.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * 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.openapi.cmd; + +import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; +import org.apache.commons.lang3.StringUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.OUT; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.TEST_DISTRIBUTION_PATH; +import static io.ballerina.openapi.TestUtil.assertOnErrorStream; + +/** + * This test class is for storing the schema related integrations to negative scenarios. + */ +public class SchemaGenerationNegativeTests extends OpenAPITest { + public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); + public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/schema"); + + @BeforeClass + public void setupDistributions() throws IOException { + TestUtil.cleanDistribution(); + } + + @Test(description = "Tests with record field has constraint value with string type with unsupported patterns.") + public void constraintWithUnsupportedStringPattern() throws IOException, InterruptedException { + String openapiFilePath = "unsupported_string_pattern.yaml"; + Process process = getProcessForClientGeneration(openapiFilePath); + + String out = "WARNING: skipped generation for unsupported pattern in ballerina: " + + "^(?!(.*[\\\"\\*\\\\\\>\\<\\?\\/\\:\\|]+.*)|(.*[\\.]?.*[\\.]+$)|(.*[ ]+$)) \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2," + + "49}[a-zA-Z0-9]$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: (https?:\\/\\/)?([\\da-z\\.-]+)\\." + + "([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^[A-Za-z\\-\\_\\/]+$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^.*(?=.{6,1000})(?=.*\\d)" + + "(?=.*[a-z])(?=.*[A-Z]).*$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^[\\x09\\x0A\\x0D\\x20\\x23\\x2D\\" + + "x30-\\x39\\x40-\\x5A\\x5E-\\x5F\\x61-\\x7A\\x7E-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]{1,100}$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^[a-z0-9\\-\\_\\.]+$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: ^(?!\\s)(.*)(\\S)$ \n" + + "WARNING: skipped generation for unsupported pattern in ballerina: \\+[0-9]{1,3}\\-[0-9()+\\-]{1,30} "; + //Thread for wait out put generate + Thread.sleep(5000); + // compare generated file has not included constraint annotation for scenario record field. + compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", "schema/unsupported_string_pattern.bal"); + process.waitFor(); + assertOnErrorStream(process, out); + } + + @Test(description = "Tests with record field has constraint value with string type with " + + "non-ECMA flavoured patterns.") + public void constraintWithStringInvalidPattern() throws IOException, InterruptedException { + String openapiFilePath = "non_ecma_pattern_string.yaml"; + Process process = getProcessForClientGeneration(openapiFilePath); + + String out = "WARNING: skipped generation for non-ECMA flavoured pattern: (A)?(?(1)B|C) "; + //Thread for wait out put generate + Thread.sleep(5000); + // compare generated file has not included constraint annotation for scenario record field. + compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", "schema/non_ecma_string_pattern.bal"); + process.waitFor(); + assertOnErrorStream(process, out); + } + + public Process getProcessForClientGeneration(String openapiFilePath) throws IOException { + List buildArgs = new LinkedList<>(); + buildArgs.add(0, "openapi"); + buildArgs.add("-i"); + buildArgs.add(openapiFilePath); + buildArgs.add("--mode"); + buildArgs.add("client"); + buildArgs.add("-o"); + buildArgs.add(tmpDir.toString()); + + String balFile = "bal"; + + if (System.getProperty("os.name").startsWith("Windows")) { + balFile = "bal.bat"; + } + buildArgs.add(0, TEST_DISTRIBUTION_PATH.resolve(DISTRIBUTION_FILE_NAME).resolve("bin") + .resolve(balFile).toString()); + OUT.println("Executing: " + StringUtils.join(buildArgs, ' ')); + ProcessBuilder pb = new ProcessBuilder(buildArgs); + pb.directory(TEST_RESOURCE.toFile()); + return pb.start(); + } +} diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationTests.java new file mode 100644 index 000000000..bca7ab75e --- /dev/null +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/SchemaGenerationTests.java @@ -0,0 +1,90 @@ +package io.ballerina.openapi.cmd; + +import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; +import org.apache.commons.lang3.StringUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +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.LinkedList; +import java.util.List; + +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.OUT; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.TEST_DISTRIBUTION_PATH; + +/** + * This test class is for storing the schema related integrations. + */ +public class SchemaGenerationTests extends OpenAPITest { + public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); + public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/schema"); + + @BeforeClass + public void setupDistributions() throws IOException { + TestUtil.cleanDistribution(); + } + @Test(description = "Tests with record field has constraint value with union type.") + public void constraintWithUnionType() throws IOException, InterruptedException { + String openapiFilePath = "union_type.yaml"; + List buildArgs = new LinkedList<>(); + buildArgs.add(0, "openapi"); + buildArgs.add("-i"); + buildArgs.add(openapiFilePath); + buildArgs.add("--mode"); + buildArgs.add("client"); + buildArgs.add("-o"); + buildArgs.add(tmpDir.toString()); + + String balFile = "bal"; + + if (System.getProperty("os.name").startsWith("Windows")) { + balFile = "bal.bat"; + } + buildArgs.add(0, TEST_DISTRIBUTION_PATH.resolve(DISTRIBUTION_FILE_NAME).resolve("bin") + .resolve(balFile).toString()); + OUT.println("Executing: " + StringUtils.join(buildArgs, ' ')); + ProcessBuilder pb = new ProcessBuilder(buildArgs); + pb.directory(TEST_RESOURCE.toFile()); + Process process = pb.start(); + + // Todo: Set a proper tes for capture the terminal out come for cli command. + String out = "WARNING: constraints in OpenAPI contract will be ignored for the field `service_class`," + + " as constraints are not supported on Ballerina union types\n" + + "WARNING: constraints in OpenAPI contract will be ignored for the field `tax_rates`, " + + "as constraints are not supported on Ballerina union types\n" + + "WARNING: constraints in OpenAPI contract will be ignored for the field `tax_rates_anyOf`," + + " as constraints are not supported on Ballerina union types\n" + + "WARNING: constraints in OpenAPI contract will be ignored for the field `tax_rates_oneOF_array`," + + " as constraints are not supported on Ballerina union types\n" + + "WARNING: constraints in OpenAPI contract will be ignored for the field `tax_rates_anyOf_array`, as " + + "constraints are not supported on Ballerina union types"; + //Thread for wait out put generate + Thread.sleep(5000); + // compare generated file has not included constraint annotation for scenario record field. + compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", "schema/union.bal"); + process.waitFor(); + } + + @Test + public void testConstraintWithArrayTypeWhenNullableEnable() throws IOException, InterruptedException { + String openapiFilePath = "array.yaml"; + List buildArgs = new LinkedList<>(); + buildArgs.add("-i"); + buildArgs.add(openapiFilePath); + buildArgs.add("--mode"); + buildArgs.add("client"); + buildArgs.add("-o"); + buildArgs.add(tmpDir.toString()); + buildArgs.add("--nullable"); + boolean successful = TestUtil.executeOpenAPI(DISTRIBUTION_FILE_NAME, TEST_RESOURCE, buildArgs); + Assert.assertTrue(Files.exists(Paths.get(tmpDir.toString()).resolve("types.bal"))); + compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", "schema/array.bal"); + } +} diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGenerationTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGenerationTests.java new file mode 100644 index 000000000..37ee5e361 --- /dev/null +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGenerationTests.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022 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.openapi.cmd; + +import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.extension.build.ValidatorTests.WHITESPACE_PATTERN; + +/** + * This test class created for contain the OpenAPI to Ballerina service generator return type checks. + */ +public class ServiceGenerationTests extends OpenAPITest { + public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); + public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/service/return"); + + @Test(dataProvider = "returnSampleProvider") + public void testResponseStatusCodeRecord(String openapiFilePath, String expectedFilePath) + throws IOException, InterruptedException { + List buildArgs = new LinkedList<>(); + buildArgs.add("-i"); + buildArgs.add("swagger/" + openapiFilePath); + buildArgs.add("--mode"); + buildArgs.add("service"); + buildArgs.add("-o"); + buildArgs.add(tmpDir.toString()); + boolean successful = TestUtil.executeOpenAPI(DISTRIBUTION_FILE_NAME, TEST_RESOURCE, buildArgs); + compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", expectedFilePath); + } + + @Test(description = "Negative test to assert warnings on unsupported OAS type formats") + public void testUnsupportedOASFormatTests() throws IOException { + List buildArgs = new LinkedList<>(); + buildArgs.add("-i"); + buildArgs.add("swagger/" + "unsupported_oas_format.yaml"); + buildArgs.add("--mode"); + buildArgs.add("service"); + buildArgs.add("-o"); + buildArgs.add(tmpDir.toString()); + InputStream successful = TestUtil.executeOpenAPIToTestWarnings( + DISTRIBUTION_FILE_NAME, TEST_RESOURCE, buildArgs); + String msg = "WARNING: unsupported format `date` will be skipped when generating the counterpart " + + "Ballerina type for openAPI schema type: `string`"; + try (BufferedReader br = new BufferedReader(new InputStreamReader(successful))) { + Stream logLines = br.lines(); + String generatedLog = logLines.collect(Collectors.joining(System.lineSeparator())); + logLines.close(); + generatedLog = (generatedLog.trim()).replaceAll(WHITESPACE_PATTERN, ""); + msg = (msg.trim()).replaceAll(WHITESPACE_PATTERN, ""); + if (generatedLog.contains(msg)) { + Assert.assertTrue(true); + } else { + Assert.fail("Unexpected service generation output."); + } + } + } + + @DataProvider(name = "returnSampleProvider") + public Object[][] dataProvider() { + return new Object[][]{ + {"content_schema_null.yaml", "service/return/ballerina/content_schema_null.bal"}, + {"content_schema_has_one_of_type.yaml", "service/return/ballerina/" + + "content_schema_has_one_of_type.bal"}, + {"multiple_media_types_for_one_response_code.yaml", "service/return/ballerina/" + + "multiple_mediatype_for_one_response_code.bal"}, // + // one response code has multiple media types (content types) + {"response_has_inline_record.yaml", "service/return/ballerina/" + + "response_has_inline_record.bal"}, + {"same_response.yaml", "service/return/ballerina/same_response.bal"}, // Two resources have + // same error code with same body type for return type. + {"unsupported_payload_type.yaml", "service/return/ballerina/unsupported_payload_type.bal"}, + {"response_has_inline_additional_properties.yaml", + "service/return/ballerina/response_has_inline_additional_properties.bal"}, + {"post_method.yaml", "service/return/ballerina/post_method.bal"} + }; + } +} diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGeneratorReturnTypeTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGeneratorReturnTypeTests.java deleted file mode 100644 index ea22eccf3..000000000 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/cmd/ServiceGeneratorReturnTypeTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2022 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.openapi.cmd; - -import io.ballerina.openapi.OpenAPITest; -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 java.util.LinkedList; -import java.util.List; - -import static io.ballerina.openapi.cmd.TestUtil.DISTRIBUTIONS_DIR; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCES_PATH; - -/** - * This test class created for contain the OpenAPI to Ballerina service generator return type checks. - */ -public class ServiceGeneratorReturnTypeTests extends OpenAPITest { - public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); - public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/service/return"); - - @Test(dataProvider = "returnSampleProvider") - public void testResponseStatusCodeRecord(String openapiFilePath, String expectedFilePath) - throws IOException, InterruptedException { - List buildArgs = new LinkedList<>(); - buildArgs.add("-i"); - buildArgs.add("swagger/" + openapiFilePath); - buildArgs.add("--mode"); - buildArgs.add("service"); - buildArgs.add("-o"); - buildArgs.add(tmpDir.toString()); - boolean successful = TestUtil.executeOpenAPI(DISTRIBUTION_FILE_NAME, TEST_RESOURCE, buildArgs); - compareGeneratedSyntaxTreewithExpectedSyntaxTree("types.bal", expectedFilePath); - } - - @DataProvider(name = "returnSampleProvider") - public Object[][] dataProvider() { - return new Object[][]{ - {"content_schema_null.yaml", "content_schema_null.bal"}, // When the response content payload schema - // type is null - {"content_schema_has_one_of_type.yaml", "content_schema_has_one_of_type.bal"}, // content type has - // one of type schemas - {"multiple_media_types_for_one_response_code.yaml", "multiple_mediatype_for_one_response_code.bal"}, // - // one response code has multiple media types (content types) - {"response_has_inline_record.yaml", "response_has_inline_record.bal"}, // Response has inline object - // schema for content schema. - {"same_response.yaml", "same_response.bal"} // Two resources have same error code with same body type - // for return type. - }; - } -} diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/BuildExtensionTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/BuildExtensionTests.java index eb102e78e..ad60a14ee 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/BuildExtensionTests.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/BuildExtensionTests.java @@ -17,7 +17,7 @@ */ package io.ballerina.openapi.extension.build; -import io.ballerina.openapi.cmd.TestUtil; +import io.ballerina.openapi.TestUtil; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -29,10 +29,10 @@ import java.util.LinkedList; import java.util.List; -import static io.ballerina.openapi.cmd.TestUtil.DISTRIBUTIONS_DIR; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCE; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCES_PATH; -import static io.ballerina.openapi.cmd.TestUtil.executeBuild; +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCE; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.executeBuild; /** * These tests are for capture the `--export-openapi` flag in distribution. @@ -61,13 +61,13 @@ public void flagWithBuildOption() throws IOException, InterruptedException { Assert.assertTrue(Files.exists(TEST_RESOURCE.resolve("project_2/target/openapi/greeting_openapi.yaml"))); } - @Test(description = "Check --export-openapi flag with graphQl service") + @Test(description = "Check --export-openapi flag with graphQl service", enabled = false) public void withNonHttpServiceWithBuildOption() throws IOException, InterruptedException { List buildArgs = new LinkedList<>(); buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_3"), buildArgs); - Assert.assertTrue(Files.exists(RESOURCE.resolve("project_3/target/openapi/greeting_openapi.yaml"))); + Assert.assertTrue(Files.exists(RESOURCE.resolve("build/project_3/target/openapi/greeting_openapi.yaml"))); } @Test(description = "Check --export-openapi flag with package has service on module") @@ -76,8 +76,8 @@ public void buildOptionWithSeparateModule() throws IOException, InterruptedExcep buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_4"), buildArgs); - Assert.assertTrue(Files.exists(RESOURCE.resolve("project_4/target/openapi/greeting_openapi.yaml"))); - Assert.assertTrue(Files.exists(RESOURCE.resolve("project_4/target/openapi/mod_openapi.yaml"))); + Assert.assertTrue(Files.exists(RESOURCE.resolve("build/project_4/target/openapi/greeting_openapi.yaml"))); + Assert.assertTrue(Files.exists(RESOURCE.resolve("build/project_4/target/openapi/mod_openapi.yaml"))); } @Test(description = "Check --export-openapi flag with single service file build", enabled = false) @@ -94,7 +94,7 @@ public void buildOptionWithGrpcService() throws IOException, InterruptedExceptio buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_6"), buildArgs); - Assert.assertFalse(Files.exists(RESOURCE.resolve("project_6/target/openapi/"))); + Assert.assertFalse(Files.exists(RESOURCE.resolve("build/project_6/target/openapi/"))); } @Test(description = "Check --export-openapi flag with webHub service") @@ -103,7 +103,7 @@ public void buildOptionWithWebHub() throws IOException, InterruptedException { buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_7"), buildArgs); - Assert.assertFalse(Files.exists(RESOURCE.resolve("project_7/target/openapi/"))); + Assert.assertFalse(Files.exists(RESOURCE.resolve("build/project_7/target/openapi/"))); } @Test(description = "Base path with special characters") @@ -112,7 +112,7 @@ public void basePathWithSpecialCharacter() throws IOException, InterruptedExcept buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_8"), buildArgs); - Assert.assertTrue(Files.exists(RESOURCE.resolve("project_8/target/openapi/" + + Assert.assertTrue(Files.exists(RESOURCE.resolve("build/project_8/target/openapi/" + "well_known_smart_configuration_openapi.yaml"))); } @@ -122,7 +122,7 @@ public void basePathWithUnicodeCharacter() throws IOException, InterruptedExcept buildArgs.add("--export-openapi"); boolean successful = executeBuild(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_9"), buildArgs); - Assert.assertTrue(Files.exists(RESOURCE.resolve("project_9/target/openapi/ชื่อ_openapi.yaml"))); + Assert.assertTrue(Files.exists(RESOURCE.resolve("build/project_9/target/openapi/ชื่อ_openapi.yaml"))); } private void executeCommand(String resourcePath) throws IOException, InterruptedException { List buildArgs = new LinkedList<>(); diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/ValidatorTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/ValidatorTests.java index 561b88a3a..d9479c965 100644 --- a/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/ValidatorTests.java +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/extension/build/ValidatorTests.java @@ -17,7 +17,7 @@ */ package io.ballerina.openapi.extension.build; -import io.ballerina.openapi.cmd.TestUtil; +import io.ballerina.openapi.TestUtil; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -33,8 +33,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static io.ballerina.openapi.cmd.TestUtil.DISTRIBUTIONS_DIR; -import static io.ballerina.openapi.cmd.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; /** * This test class is for contain the openapi validator plugin tests. diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginNegativeTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginNegativeTests.java new file mode 100644 index 000000000..f9a1c043a --- /dev/null +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginNegativeTests.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.idl.client; + +import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCE; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.executeRun; +import static io.ballerina.openapi.extension.build.ValidatorTests.WHITESPACE_PATTERN; + +/** + * Negative tests for OpenAPI client IDL import. + */ +public class IDLClientGenPluginNegativeTests extends OpenAPITest { + + public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); + public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/client-idl-projects"); + @BeforeClass + public void setupDistributions() throws IOException { + TestUtil.cleanDistribution(); + } + + @Test + public void testClientDeclarationInsideFunction() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_04"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_04/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(2:5,2:11)] 'client' qualifier not allowed"; + assertOnErrorStream(process, msg); + } + + @Test(description = "Here uses the graphQl yaml as non openapi client") + public void testNonOpenAPIClientDeclaration() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_07"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_07/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(1:1,1:176)] no matching plugin found for client declaration"; + assertOnErrorStream(process, msg); + } + + @Test + public void testInvalidSwaggerRemotePath() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_10"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_10/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(1:1,1:132)] unable to get resource from uri, reason: "; + assertOnErrorStream(process, msg); + } + + @Test + public void testInvalidSwaggerLocalPath() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_11"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_11/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(1:1,1:31)] could not locate the file:"; + assertOnErrorStream(process, msg); + } + + @Test + public void testInvalidSwaggerContract() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_12"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_12/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(1:1,1:30)] OpenAPI definition has errors:"; + assertOnErrorStream(process, msg); + } + + //TODO: enable this test after figuring out the fail reason. + @Test(description = "Disable this test due to fail in test workflow, this has been tested by manual and it " + + "passed as expected", enabled = false) + public void testUnsupportedSwaggerVersion() throws IOException, InterruptedException { + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_13"), + new ArrayList<>()); + File dir = new File(RESOURCE.resolve("client-idl-projects/project_13/generated/").toString()); + Assert.assertFalse(dir.exists()); + String msg = "ERROR [main.bal:(2:5,2:119)] provided openAPI contract version is not supported"; + assertOnErrorStream(process, msg); + } + + private static void assertOnErrorStream(Process process, String msg) throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + Stream logLines = br.lines(); + String generatedLog = logLines.collect(Collectors.joining("\n")); + logLines.close(); + String formattedGeneratedLog = (generatedLog.trim()).replaceAll(WHITESPACE_PATTERN, ""); + String formattedMessage = msg.trim().replaceAll(WHITESPACE_PATTERN, ""); + Assert.assertTrue(formattedGeneratedLog.contains(formattedMessage), + String.format("compiler output doesn't contain the expected" + + " output: %s : generated output : %s", msg, generatedLog)); + } + } +} diff --git a/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginTests.java b/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginTests.java new file mode 100644 index 000000000..aacff40f4 --- /dev/null +++ b/openapi-integration-tests/src/test/java/io/ballerina/openapi/idl/client/IDLClientGenPluginTests.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). 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.openapi.idl.client; + +import io.ballerina.openapi.OpenAPITest; +import io.ballerina.openapi.TestUtil; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +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.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.openapi.TestUtil.DISTRIBUTIONS_DIR; +import static io.ballerina.openapi.TestUtil.RESOURCE; +import static io.ballerina.openapi.TestUtil.RESOURCES_PATH; +import static io.ballerina.openapi.TestUtil.executeRun; +import static io.ballerina.openapi.TestUtil.getMatchingFiles; + +/** + * This class is for client IDL integration tests. + */ +public class IDLClientGenPluginTests extends OpenAPITest { + + public static final String DISTRIBUTION_FILE_NAME = DISTRIBUTIONS_DIR.toString(); + public static final Path TEST_RESOURCE = Paths.get(RESOURCES_PATH.toString() + "/client-idl-projects"); + + @BeforeClass + public void setupDistributions() throws IOException { + TestUtil.cleanDistribution(); + } + + @Test + public void testValidSwaggerContract() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("bar"); + File[] matchingFiles = getMatchingFiles("project_01", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test + public void testClientDeclarationWithOutAnnotation() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("foo"); + File[] matchingFiles = getMatchingFiles("project_02", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test + public void testClientDeclarationWithAnnotation() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("bar"); + File[] matchingFiles = getMatchingFiles("project_03", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test + public void testModuleLevelClientDeclarationNode() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("bar"); + File[] matchingFiles = getMatchingFiles("project_05", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test(description = "When multiple client declarations have same annotation") + public void testMultipleClientsWithSameAnnotation() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("foo"); + File[] matchingFiles = getMatchingFiles("project_06", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test + public void testInvokeAPIFromGeneratedClient() throws IOException, InterruptedException { + Process successful = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_08"), + new ArrayList<>()); + Assert.assertEquals(successful.waitFor(), 0); + } + + @Test(description = "test client declarations with local YAML contract paths") + public void testWithLocalPathYAML() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("bar"); + File[] matchingFiles = getMatchingFiles("project_09", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test(description = "test client declarations with local JSON contract paths") + public void testWithLocalPathJSON() throws IOException, InterruptedException { + List ids = new LinkedList<>(); + ids.add("bar"); + File[] matchingFiles = getMatchingFiles("project_14", ids); + Assert.assertNotNull(matchingFiles); + Assert.assertEquals(matchingFiles.length, 1); + } + + @Test + public void testWithClientClassName() throws IOException, InterruptedException { + String classContent = "public isolated client class Client {"; + Process process = executeRun(DISTRIBUTION_FILE_NAME, TEST_RESOURCE.resolve("project_15"), new LinkedList<>()); + process.waitFor(); + Path clientFile = + Path.of(RESOURCE.resolve("client-idl-projects/project_15/generated/bar/client.bal").toString()); + Stream expectedServiceLines = Files.lines(clientFile); + String generatedContent = expectedServiceLines.collect(Collectors.joining(System.lineSeparator())); + expectedServiceLines.close(); + Assert.assertTrue((generatedContent.trim()).replaceAll("\\s+", "") + .contains(classContent.trim().replaceAll("\\s+", ""))); + } +} diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/Ballerina.toml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/Ballerina.toml new file mode 100644 index 000000000..d3cc51d4b --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org= "ballerina" +name= "openapi" +version= "2.0.0" diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/result.yaml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/result.yaml new file mode 100644 index 000000000..f88b7490b --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/result.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/service.bal b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/service.bal new file mode 100644 index 000000000..36a83b3d3 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation/service.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +# A service representing a network-accessible API +# bound to port `9090`. +@display { + label: "SampleRest2", + id: "SampleRest2-a0419d61-26b8-48ad-8696-3a16c9958522" +} +service / on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/Ballerina.toml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/Ballerina.toml new file mode 100644 index 000000000..d3cc51d4b --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org= "ballerina" +name= "openapi" +version= "2.0.0" diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/result.yaml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/result.yaml new file mode 100644 index 000000000..1c55a4b07 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/result.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.1 +info: + title: Payload + version: 2.0.0 +servers: + - url: "{server}:{port}/payload" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/service.bal b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/service.bal new file mode 100644 index 000000000..b0fef3546 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_with_base_path/service.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +# A service representing a network-accessible API +# bound to port `9090`. +@display { + label: "SampleRest2", + id: "SampleRest2-a0419d61-26b8-48ad-8696-3a16c9958522" +} +service /payload on new http:Listener(9090) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/Ballerina.toml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/Ballerina.toml new file mode 100644 index 000000000..d3cc51d4b --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org= "ballerina" +name= "openapi" +version= "2.0.0" diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/result.yaml b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/result.yaml new file mode 100644 index 000000000..fa4e75654 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/result.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.1 +info: + title: Service File Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}" + variables: + server: + default: http://localhost + port: + default: "9098" +paths: + /greeting: + get: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + responses: + "200": + description: Ok + content: + text/plain: + schema: + type: string + "500": + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' +components: + schemas: + ErrorPayload: + type: object + properties: + reason: + type: string + description: Reason phrase + path: + type: string + description: Request path + method: + type: string + description: Method type of the request + message: + type: string + description: Error message + timestamp: + type: string + description: Timestamp of the error + status: + type: integer + description: Relevant HTTP status code + format: int32 diff --git a/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/service_file.bal b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/service_file.bal new file mode 100644 index 000000000..6352958a9 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/ballerina_sources/project_non_openapi_annotation_without_base_path/service_file.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +# A service representing a network-accessible API +# bound to port `9090`. +@display { + label: "SampleRest2", + id: "SampleRest2-a0419d61-26b8-48ad-8696-3a16c9958522" +} +service on new http:Listener(9098) { + + # A resource for generating greetings + # + name - the input string name + # + return - string name with hello message or error + resource function get greeting(string name) returns string|error { + // Send a response back to the caller. + if name is "" { + return error("name should not be empty!"); + } + return "Hello, " + name; + } +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/main.bal new file mode 100644 index 000000000..d6bb4a209 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/main.bal @@ -0,0 +1,4 @@ +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as bar; +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/openapi.yaml new file mode 100644 index 000000000..f5d6142f8 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_01/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_02/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_02/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_02/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_02/main.bal new file mode 100644 index 000000000..ffc7af250 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_02/main.bal @@ -0,0 +1,5 @@ +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as foo; + +public function main() { + foo:client x; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/license.txt b/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/license.txt new file mode 100644 index 000000000..44b7f2743 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/license.txt @@ -0,0 +1,2 @@ +//abc abc +//abc abc \ No newline at end of file diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/main.bal new file mode 100644 index 000000000..5324da7d7 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_03/main.bal @@ -0,0 +1,14 @@ +import ballerina/openapi; + +@openapi:ClientConfig { + tags:["abc", "ads"], + operations: ["o1"], + nullable: false, + isResource: false, + license: "license.txt" +} +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_04/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_04/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_04/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_04/main.bal new file mode 100644 index 000000000..152c8c34f --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_04/main.bal @@ -0,0 +1,4 @@ +public function main() { + client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as foo; + foo:client x; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_05/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_05/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_05/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_05/main.bal new file mode 100644 index 000000000..c8670b223 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_05/main.bal @@ -0,0 +1,5 @@ +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_06/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_06/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_06/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_06/main.bal new file mode 100644 index 000000000..5554e6408 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_06/main.bal @@ -0,0 +1,20 @@ +import ballerina/openapi; + +@openapi:ClientConfig { + tags:["abc", "ads"], + operations: ["o1"], + nullable: false +} +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as foo; + +@openapi:ClientConfig { + tags:["abc", "ads"], + operations: ["o1"], + nullable: false +} +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap/openapi.yaml" as bar; + +public function main() { + bar:client y; + foo:client x; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_07/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_07/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_07/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_07/main.bal new file mode 100644 index 000000000..268e7070e --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_07/main.bal @@ -0,0 +1,5 @@ +client "https://raw.githubusercontent.com/ballerina-platform/graphql-tools/main/graphql-cli/src/test/resources/specs/graphql-config-with-basic-auth-client-config.yaml" as foo; + +public function main() { + foo:client x; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_08/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_08/Ballerina.toml new file mode 100644 index 000000000..e69de29bb diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_08/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_08/main.bal new file mode 100644 index 000000000..8e88847dc --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_08/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; +import ballerina/openapi; + +@openapi:ClientConfig { + operations: ["getUSCountiesStatus"], + nullable: true +} +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/covid19/openapi.yaml" as bar; + +public function main() returns error? { + bar:client countryClient = check new (); + bar:CovidJHUCounties country = check countryClient->/v3/covid\-19/jhucsse/counties.get; + if country is bar:CovidJHUCounty[] { + io:println(country[0]); + } +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/main.bal new file mode 100644 index 000000000..5a58da41f --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/main.bal @@ -0,0 +1,5 @@ +client "openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/openapi.yaml new file mode 100644 index 000000000..f5d6142f8 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_09/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/main.bal new file mode 100644 index 000000000..4d3747421 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/main.bal @@ -0,0 +1,5 @@ +client "https://raw.githubusercontent.com/ballerina-platform/openapi-connectors/main/openapi/openweathermap01/openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/openapi.yaml new file mode 100644 index 000000000..f5d6142f8 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_10/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/main.bal new file mode 100644 index 000000000..e1d9c107e --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/main.bal @@ -0,0 +1,5 @@ +client "openapi2.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/openapi.yaml new file mode 100644 index 000000000..f5d6142f8 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_11/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/main.bal new file mode 100644 index 000000000..5a58da41f --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/main.bal @@ -0,0 +1,5 @@ +client "openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/openapi.yaml new file mode 100644 index 000000000..f57c88172 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_12/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users/{id}: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/Ballerina.toml new file mode 100644 index 000000000..ea7803f1a --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/Ballerina.toml @@ -0,0 +1,7 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/main.bal new file mode 100644 index 000000000..a5751fe65 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/main.bal @@ -0,0 +1,5 @@ +client "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v2.0/yaml/petstore.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/openapi.yaml new file mode 100644 index 000000000..84839c338 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_13/openapi.yaml @@ -0,0 +1,15 @@ +swagger: 2.0.0 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +host: petstore.swagger.io +basePath: /v1 +paths: + /users/{id}: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/main.bal new file mode 100644 index 000000000..e3a7412a7 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/main.bal @@ -0,0 +1,5 @@ +client "openapi.json" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/openapi.json b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/openapi.json new file mode 100644 index 000000000..490c582fb --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_14/openapi.json @@ -0,0 +1,32 @@ +{ + "openapi": "3.0.1", + "info": { + "title": " ", + "version": "1.0.0" + }, + "servers": [ + { + "url": "localhost:9090/" + } + ], + "paths": { + "/greeting": { + "get": { + "operationId": "operation1_get_/greeting", + "responses": { + "200": { + "description": "Ok", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + } + }, + "components": {} +} \ No newline at end of file diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/Ballerina.toml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/Ballerina.toml new file mode 100644 index 000000000..005e00d52 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "openapi_client_idl_test" +name = "project_1" +version = "0.1.0" + +[build-options] +observabilityIncluded = true + diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/main.bal b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/main.bal new file mode 100644 index 000000000..5a58da41f --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/main.bal @@ -0,0 +1,5 @@ +client "openapi.yaml" as bar; + +public function main() { + bar:client y; +} diff --git a/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/openapi.yaml b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/openapi.yaml new file mode 100644 index 000000000..f5d6142f8 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/client-idl-projects/project_15/openapi.yaml @@ -0,0 +1,15 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + get: + summary: Returns a list of users. + description: Optional extended description in Markdown. + responses: + '200': + description: OK diff --git a/openapi-integration-tests/src/test/resources/client/expected_client.bal b/openapi-integration-tests/src/test/resources/client/expected_client.bal index e20c16848..62f936b2d 100644 --- a/openapi-integration-tests/src/test/resources/client/expected_client.bal +++ b/openapi-integration-tests/src/test/resources/client/expected_client.bal @@ -5,11 +5,33 @@ public isolated client class Client { final http:Client clientEp; # Gets invoked to initialize the `connector`. # - # + clientConfig - The configurations to be used when initializing 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(http:ClientConfiguration clientConfig = {}, string serviceUrl = "https://api.example.com") returns error? { - http:Client httpEp = check new (serviceUrl, clientConfig); + public isolated function init(ConnectionConfig config = {}, string serviceUrl = "https://api.example.com") returns error? { + http:ClientConfiguration httpClientConfig = {httpVersion: config.httpVersion, timeout: config.timeout, forwarded: config.forwarded, poolConfig: config.poolConfig, compression: config.compression, circuitBreaker: config.circuitBreaker, retryConfig: config.retryConfig, validation: config.validation}; + do { + if config.http1Settings is ClientHttp1Settings { + ClientHttp1Settings settings = check config.http1Settings.ensureType(ClientHttp1Settings); + httpClientConfig.http1Settings = {...settings}; + } + if config.http2Settings is http:ClientHttp2Settings { + httpClientConfig.http2Settings = check config.http2Settings.ensureType(http:ClientHttp2Settings); + } + if config.cache is http:CacheConfig { + httpClientConfig.cache = check config.cache.ensureType(http:CacheConfig); + } + if config.responseLimits is http:ResponseLimitConfigs { + httpClientConfig.responseLimits = check config.responseLimits.ensureType(http:ResponseLimitConfigs); + } + if config.secureSocket is http:ClientSecureSocket { + httpClientConfig.secureSocket = check config.secureSocket.ensureType(http:ClientSecureSocket); + } + if config.proxy is http:ProxyConfig { + httpClientConfig.proxy = check config.proxy.ensureType(http:ProxyConfig); + } + } + http:Client httpEp = check new (serviceUrl, httpClientConfig); self.clientEp = httpEp; return; } diff --git a/openapi-integration-tests/src/test/resources/schema/array.bal b/openapi-integration-tests/src/test/resources/schema/array.bal new file mode 100644 index 000000000..4cae71575 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/array.bal @@ -0,0 +1,62 @@ +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type User record { + string? id?; + string[]? address?; +}; diff --git a/openapi-integration-tests/src/test/resources/schema/array.yaml b/openapi-integration-tests/src/test/resources/schema/array.yaml new file mode 100644 index 000000000..6ccd43a7b --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/array.yaml @@ -0,0 +1,33 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /users: + post: + summary: Returns a list of users. + description: Optional extended description in Markdown. + operationId: "01" + responses: + '200': + description: OK + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/User" +components: + schemas: + User: + type: object + properties: + id: + type: string + address: + type: array + items: + type: string + maxItems: 5 diff --git a/openapi-integration-tests/src/test/resources/schema/non_ecma_pattern_string.yaml b/openapi-integration-tests/src/test/resources/schema/non_ecma_pattern_string.yaml new file mode 100644 index 000000000..204090478 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/non_ecma_pattern_string.yaml @@ -0,0 +1,49 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: string + hobby: + type: string + id: + type: integer + maximum: 5 + pcre: + description: PCRE regex pattern that doesn't support in ECMA + type: string + pattern: (A)?(?(1)B|C) diff --git a/openapi-integration-tests/src/test/resources/schema/non_ecma_string_pattern.bal b/openapi-integration-tests/src/test/resources/schema/non_ecma_string_pattern.bal new file mode 100644 index 000000000..437d6a49e --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/non_ecma_string_pattern.bal @@ -0,0 +1,67 @@ +import ballerina/constraint; +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type Person record { + string name?; + string hobby?; + @constraint:Int {maxValue: 5} + int id; + # PCRE regex pattern that doesn't support in ECMA + string pcre?; +}; diff --git a/openapi-integration-tests/src/test/resources/schema/union.bal b/openapi-integration-tests/src/test/resources/schema/union.bal new file mode 100644 index 000000000..0a610eb25 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/union.bal @@ -0,0 +1,81 @@ +import ballerina/constraint; +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +@constraint:String {maxLength: 5000} +public type TaxratesItemsString string; + +@constraint:String {maxLength: 5000} +public type TaxratesanyofItemsString string; + +public type TaxratesoneofarrayItemsNull string|int; + +public type TaxratesanyofarrayItemsNull int|string; + +public type Person record { + # scenario 01 - field with nullable. + 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/openapi-integration-tests/src/test/resources/schema/union_type.yaml b/openapi-integration-tests/src/test/resources/schema/union_type.yaml new file mode 100644 index 000000000..4afa848ec --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/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/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.bal b/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.bal new file mode 100644 index 000000000..226cc373c --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.bal @@ -0,0 +1,73 @@ +import ballerina/constraint; +import ballerina/http; + +# Provides a set of configurations for controlling the behaviours when communicating with a remote HTTP endpoint. +@display {label: "Connection Config"} +public type ConnectionConfig record {| + # The HTTP version understood by the client + http:HttpVersion httpVersion = http:HTTP_2_0; + # Configurations related to HTTP/1.x protocol + ClientHttp1Settings http1Settings?; + # Configurations related to HTTP/2 protocol + http:ClientHttp2Settings http2Settings?; + # The maximum time to wait (in seconds) for a response before closing the connection + decimal timeout = 60; + # The choice of setting `forwarded`/`x-forwarded` header + string forwarded = "disable"; + # Configurations associated with request pooling + http:PoolConfiguration poolConfig?; + # HTTP caching related configurations + http:CacheConfig cache?; + # Specifies the way of handling compression (`accept-encoding`) header + http:Compression compression = http:COMPRESSION_AUTO; + # Configurations associated with the behaviour of the Circuit Breaker + http:CircuitBreakerConfig circuitBreaker?; + # Configurations associated with retrying + http:RetryConfig retryConfig?; + # Configurations associated with inbound response size limits + http:ResponseLimitConfigs responseLimits?; + # SSL/TLS-related options + http:ClientSecureSocket secureSocket?; + # Proxy server related options + http:ProxyConfig proxy?; + # Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default + boolean validation = true; +|}; + +# Provides settings related to HTTP/1.x protocol. +public type ClientHttp1Settings record {| + # Specifies whether to reuse a connection for multiple requests + http:KeepAlive keepAlive = http:KEEPALIVE_AUTO; + # The chunking behaviour of the request + http:Chunking chunking = http:CHUNKING_AUTO; + # Proxy server related options + ProxyConfig proxy?; +|}; + +# Proxy server configurations to be used with the HTTP client endpoint. +public type ProxyConfig record {| + # Host name of the proxy server + string host = ""; + # Proxy server port + int port = 0; + # Proxy server username + string userName = ""; + # Proxy server password + @display {label: "", kind: "password"} + string password = ""; +|}; + +public type PersonHobbyItemsString string; + +public type Person record { + @constraint:String {maxLength: 14} + string name?; + PersonHobbyItemsString[] hobby?; + string url?; + string street?; + string net?; + string doi?; + string task?; + string ob_01?; + string ob_02?; +}; diff --git a/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.yaml b/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.yaml new file mode 100644 index 000000000..ee98e0158 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/schema/unsupported_string_pattern.yaml @@ -0,0 +1,68 @@ +openapi: 3.0.1 +info: + title: Service Openapi Yaml + version: 2.0.0 +servers: + - url: "{server}:{port}/" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /greeting: + put: + summary: A resource for generating greetings + operationId: getGreeting + parameters: + - name: name + in: query + description: the input string name + required: true + schema: + type: string + requestBody: + content: + text/plain: + schema: + $ref: "#/components/schemas/Person" + responses: + "200": + description: Ok +components: + schemas: + Person: + type: object + required: + - id + properties: + name: + type: string + pattern: ^(?!(.*[\"\*\\\>\<\?\/\:\|]+.*)|(.*[\.]?.*[\.]+$)|(.*[ ]+$)) + maxLength: 14 + hobby: + type: array + items: + type: string + pattern: ^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$ + url: + type: string + pattern: (https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + street: + type: string + pattern: ^[A-Za-z\-\_\/]+$ + net: + type: string + pattern: ^.*(?=.{6,1000})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$ + doi: + type: string + pattern: ^[\x09\x0A\x0D\x20\x23\x2D\x30-\x39\x40-\x5A\x5E-\x5F\x61-\x7A\x7E-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]{1,100}$ + task: + type: string + pattern: ^[a-z0-9\-\_\.]+$ + ob_01: + type: string + pattern: "^(?!\\s)(.*)(\\S)$" + ob_02: + type: string + pattern: '\+[0-9]{1,3}\-[0-9()+\-]{1,30}' diff --git a/openapi-integration-tests/src/test/resources/service/return/ballerina/content_schema_has_one_of_type.bal b/openapi-integration-tests/src/test/resources/service/return/ballerina/content_schema_has_one_of_type.bal index 3021dd57e..8f9410fd5 100644 --- a/openapi-integration-tests/src/test/resources/service/return/ballerina/content_schema_has_one_of_type.bal +++ b/openapi-integration-tests/src/test/resources/service/return/ballerina/content_schema_has_one_of_type.bal @@ -10,7 +10,7 @@ public type PetForm record { string lastName?; }; -public type InlineResponse200 User|Pet|PetForm; +public type Inline_response_200 User|Pet|PetForm; public type Pet record { string userName; diff --git a/openapi-integration-tests/src/test/resources/service/return/ballerina/post_method.bal b/openapi-integration-tests/src/test/resources/service/return/ballerina/post_method.bal new file mode 100644 index 000000000..ca08b87fa --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/ballerina/post_method.bal @@ -0,0 +1,6 @@ +import ballerina/http; + +public type OkString record {| + *http:Ok; + string body; +|}; diff --git a/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_additional_properties.bal b/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_additional_properties.bal new file mode 100644 index 000000000..e526415d4 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_additional_properties.bal @@ -0,0 +1,36 @@ +public type Response record {| + Inline_response_map200...; +|}; + +public type StoreInventory03Response record {| + record {|record {string name?; string place?;}...;|}...; +|}; + +public type BadRequestStoreInventory05Response record {| + *http:BadRequest; + StoreInventory05Response body; +|}; + +public type StoreInventory05Response record {| + User...; +|}; + +public type StoreInventory04Response record {| + User...; +|}; + +public type User record { + string name?; + int id?; +}; + +public type Inline_response_map200 record { + int id?; + int age?; +}; + +public type Inline_response_200 record {| + string name?; + int age?; + int...; +|}; diff --git a/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_record.bal b/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_record.bal index f0c58bae5..d1d0e1093 100644 --- a/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_record.bal +++ b/openapi-integration-tests/src/test/resources/service/return/ballerina/response_has_inline_record.bal @@ -1,8 +1,8 @@ import ballerina/http; -public type BadRequestInlineResponse400 record {| +public type BadRequestInline_response_400 record {| *http:BadRequest; - InlineResponse400 body; + Inline_response_400 body; |}; public type User record { @@ -17,7 +17,7 @@ public type PetForm record { string lastName?; }; -public type InlineResponse400 record { +public type Inline_response_400 record { # The error ID. int id?; # The error name. diff --git a/openapi-integration-tests/src/test/resources/service/return/ballerina/unsupported_payload_type.bal b/openapi-integration-tests/src/test/resources/service/return/ballerina/unsupported_payload_type.bal new file mode 100644 index 000000000..892cdc8d1 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/ballerina/unsupported_payload_type.bal @@ -0,0 +1,21 @@ +import ballerina/http; + +public type InternalServerErrorString record {| + *http:InternalServerError; + string body; +|}; + +public type OkJson record {| + *http:Ok; + json body; +|}; + +public type NotFoundAnydata record {| + *http:NotFound; + anydata body; +|}; + +public type BadRequestAnydata record {| + *http:BadRequest; + anydata body; +|}; diff --git a/openapi-integration-tests/src/test/resources/service/return/swagger/post_method.yaml b/openapi-integration-tests/src/test/resources/service/return/swagger/post_method.yaml new file mode 100644 index 000000000..a4e1680ef --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/swagger/post_method.yaml @@ -0,0 +1,66 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /user: + post: + summary: Creates a new user. + responses: + 200: + description: OK + /user02: + post: + summary: post method with 201 + operationId: post201 + responses: + 201: + description: Created + /user03: + post: + summary: post method with 201 with content + responses: + 201: + description: Created + content: + text/plain: + schema: + type: string + /user04: + post: + summary: post method with 201,200 + operationId: post + responses: + 201: + description: Created + content: + text/plain: + schema: + type: string + 200: + description: ok + content: + text/plain: + schema: + type: string diff --git a/openapi-integration-tests/src/test/resources/service/return/swagger/response_has_inline_additional_properties.yaml b/openapi-integration-tests/src/test/resources/service/return/swagger/response_has_inline_additional_properties.yaml new file mode 100644 index 000000000..51e49703e --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/swagger/response_has_inline_additional_properties.yaml @@ -0,0 +1,111 @@ +openapi: 3.0.1 +info: + title: Sample API + description: API description in Markdown. + version: 1.0.0 +servers: + - url: 'https://api.example.com' +paths: + /store/inventory: + get: + tags: + - store + description: Return has inline object property with additional property + operationId: getInventory + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + properties: + name: + type: string + age: + type: integer + additionalProperties: + type: integer + /: + get: + tags: + - store + description: Return has inline object with additional property without property + operationId: getInventory02 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: object + properties: + id: + type: integer + age: + type: integer + text/plain: + schema: + type: string + /store/inventory03: + get: + tags: + - store + description: Return has inline object with nested additional property + operationId: getInventory03 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: object + additionalProperties: + type: object + properties: + name: + type: string + place: + type: string + /store/inventory04: + get: + tags: + - store + description: Return has inline object with additional property has reference value + operationId: getInventory04 + responses: + "200": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + $ref: "#/components/schemas/User" + /store/inventory05: + get: + tags: + - store + operationId: getInventory05 + description: Return has inline object with additional property with reference and different status code + responses: + "400": + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + $ref: "#/components/schemas/User" +components: + schemas: + User: + properties: + name: + type: string + id: + type: integer diff --git a/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_oas_format.yaml b/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_oas_format.yaml new file mode 100644 index 000000000..26143a7f0 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_oas_format.yaml @@ -0,0 +1,165 @@ +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 + 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 + price: + type: number + format: currency + name: + type: string + tag: + type: string + type: + type: string + updatedDate: + type: string + format: date + additionalProperties: false + 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 + message: + type: string diff --git a/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_payload_type.yaml b/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_payload_type.yaml new file mode 100644 index 000000000..f543a5825 --- /dev/null +++ b/openapi-integration-tests/src/test/resources/service/return/swagger/unsupported_payload_type.yaml @@ -0,0 +1,132 @@ +openapi: 3.0.0 +info: + title: refComponent + description: refComponent + version: 1.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 +paths: + /store/inventory: + get: + tags: + - store + - pet + summary: Unsupported schema type, when media type is support + operationId: "id_01" + responses: + "200": + description: successful operation + content: + application/json: + example: + post: + tags: + - store + - pet + operationId: "id_02" + responses: + "200": + description: Unsupported schema type, when media type is support media type's subset + content: + application/snowflake+json: + example: + delete: + tags: + - store + - pet + operationId: "id_03" + responses: + "200": + description: When 200 status code has multiple media types + content: + application/json: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + application/zip: + example: + application/zip_0: + example: + put: + tags: + - store + - pet + operationId: "id_04" + description: When response has multiple status code + responses: + "200": + description: successful operation + content: + application/json: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "400": + description: bad request operation + content: + application/json+v: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "404": + description: bad operation + content: + application/json+v: + example: + application/snowflake+json: + example: + application/snowflake+xml: + example: + "500": + description: error operation + content: + application/json: + schema: + type: string + /store/inventory02: + get: + tags: + - store + summary: "200 status code with unsupported media type" + operationId: "id_05" + responses: + "200": + description: successful operation + content: + application/zip: + example: + put: + tags: + - store + summary: "400 status code with unsupported media type" + operationId: "id_06" + responses: + "400": + description: successful operation + content: + application/zip: + example: diff --git a/openapi-integration-tests/src/test/resources/testng.xml b/openapi-integration-tests/src/test/resources/testng.xml index 195bcc5b1..a04f3eb05 100644 --- a/openapi-integration-tests/src/test/resources/testng.xml +++ b/openapi-integration-tests/src/test/resources/testng.xml @@ -24,8 +24,12 @@ - + + + + + diff --git a/openapi-ls-extension/build.gradle b/openapi-ls-extension/build.gradle index 2f22a4fc2..ead1a09fd 100644 --- a/openapi-ls-extension/build.gradle +++ b/openapi-ls-extension/build.gradle @@ -19,7 +19,7 @@ apply from: "$rootDir/gradle/javaProject.gradle" apply plugin: "com.github.johnrengelman.shadow" -apply plugin: "java" +apply plugin: "java-library" description = "Ballerina - OpenAPI Tooling - Ballerina to OpenAPI Command" @@ -33,14 +33,12 @@ configurations { dependencies { implementation project(':openapi-bal-service') - implementation "com.fasterxml.jackson.core:jackson-databind" - implementation "io.swagger.core.v3:swagger-models" - implementation ("io.swagger.parser.v3:swagger-parser-v2-converter") { + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { exclude group: "io.swagger", module: "swagger-compat-spec-parser" exclude group: "org.slf4j", module: "slf4j-ext" exclude group: "javax.validation", module: "validation-api" } - + implementation "io.swagger.core.v3:swagger-models" implementation "javax.ws.rs:javax.ws.rs-api" implementation "com.github.jknack:handlebars" implementation "info.picocli:picocli" @@ -87,6 +85,7 @@ task copyStdlibs(type: Copy) { dependsOn(unpackStdLibs) def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE /* Standard Libraries */ configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> diff --git a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java index e8916fa5a..58e9ffb0a 100644 --- a/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java +++ b/openapi-ls-extension/src/main/java/io/ballerina/openapi/extension/OpenAPIConverterService.java @@ -30,10 +30,10 @@ import io.ballerina.openapi.converter.diagnostic.OpenAPIConverterDiagnostic; import io.ballerina.openapi.converter.model.OASResult; import io.ballerina.openapi.converter.utils.ServiceToOpenAPIConverterUtils; +import io.ballerina.projects.DiagnosticResult; import io.ballerina.projects.Document; import io.ballerina.projects.DocumentId; import io.ballerina.projects.Module; -import io.ballerina.projects.Package; import io.ballerina.projects.Project; import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; @@ -103,7 +103,7 @@ public CompletableFuture generateOpenAPIFile(OpenAPICo } else { response.setError(null); List yamlContent = ServiceToOpenAPIConverterUtils.generateOAS3Definition( - syntaxTree.get(), semanticModel.get(), null, false, + ballerinaPackage.get(), syntaxTree.get(), semanticModel.get(), null, false, Path.of(request.getDocumentFilePath())); //Response should handle if (!yamlContent.isEmpty() && (yamlContent.get(0).getOpenAPI().isPresent())) { @@ -127,35 +127,41 @@ public CompletableFuture generateOpenAPI(OpenAPIConver OpenAPIConverterResponse response = new OpenAPIConverterResponse(); Path filePath = Path.of(request.getDocumentFilePath()); Optional semanticModel = workspaceManager.semanticModel(filePath); - Optional module = workspaceManager.project(filePath); + Optional project = workspaceManager.project(filePath); if (semanticModel.isEmpty()) { response.setError("Error while generating semantic model."); return response; } - if (module.isEmpty()) { + if (project.isEmpty()) { response.setError("Error while getting the project."); return response; } - Package aPackage = module.get().currentPackage(); - Collection diagnostics = aPackage.getCompilation().diagnosticResult().diagnostics(); - boolean hasErrors = diagnostics.stream() + project = Optional.of(project.get().duplicate()); + DiagnosticResult diagnosticsFromCodeGenAndModify = project.get() + .currentPackage() + .runCodeGenAndModifyPlugins(); + boolean hasErrorsFromCodeGenAndModify = diagnosticsFromCodeGenAndModify.diagnostics().stream() .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); - if (hasErrors) { + Collection compilationDiagnostics = project.get().currentPackage() + .getCompilation().diagnosticResult().diagnostics(); + boolean hasCompilationErrors = compilationDiagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + if (hasCompilationErrors || hasErrorsFromCodeGenAndModify) { // if there are any compilation errors, do not proceed response.setError("Given Ballerina file contains compilation error(s)."); return response; } - Module defaultModule = aPackage.getDefaultModule(); - + Module defaultModule = project.get().currentPackage().getDefaultModule(); + SemanticModel updatedSemanticModel = + project.get().currentPackage().getCompilation().getSemanticModel(defaultModule.moduleId()); JsonArray specs = new JsonArray(); for (DocumentId currentDocumentID : defaultModule.documentIds()) { Document document = defaultModule.document(currentDocumentID); Optional path = defaultModule.project().documentPath(currentDocumentID); Path inputPath = path.orElse(null); SyntaxTree syntaxTree = document.syntaxTree(); - List oasResults = ServiceToOpenAPIConverterUtils.generateOAS3Definition( - syntaxTree, semanticModel.get(), null, false, inputPath); - + List oasResults = ServiceToOpenAPIConverterUtils.generateOAS3Definition(project.get(), + syntaxTree, updatedSemanticModel, null, false, inputPath); generateServiceJson(response, document.syntaxTree().filePath(), oasResults, specs); } response.setContent(specs); diff --git a/openapi-ls-extension/src/main/java/module-info.java b/openapi-ls-extension/src/main/java/module-info.java index 4514aaeeb..379402ad6 100644 --- a/openapi-ls-extension/src/main/java/module-info.java +++ b/openapi-ls-extension/src/main/java/module-info.java @@ -15,8 +15,6 @@ */ module io.ballerina.openapi.extension.openAPILSExtension { - requires com.fasterxml.jackson.core; - requires com.fasterxml.jackson.databind; requires handlebars; requires info.picocli; requires io.ballerina.lang; @@ -30,9 +28,7 @@ requires jsr305; requires org.apache.commons.io; requires org.slf4j; - requires swagger.core; requires swagger.parser; - requires swagger.models; requires swagger.parser.core; requires swagger.parser.v2.converter; requires swagger.parser.v3; diff --git a/openapi-validator/build.gradle b/openapi-validator/build.gradle index 7b24e8e57..cbeaa02c7 100644 --- a/openapi-validator/build.gradle +++ b/openapi-validator/build.gradle @@ -33,7 +33,7 @@ configurations { dependencies { implementation "io.swagger.core.v3:swagger-models" - implementation ("io.swagger.parser.v3:swagger-parser-v2-converter") { + implementation ("io.swagger.parser.v3:swagger-parser:${swaggerParserVersion}") { exclude group: "io.swagger", module: "swagger-compat-spec-parser" exclude group: "org.slf4j", module: "slf4j-ext" exclude group: "javax.validation", module: "validation-api" @@ -89,6 +89,7 @@ task copyStdlibs(type: Copy) { dependsOn(copyOpenAPI) def ballerinaDist = "$project.buildDir/extracted-distribution/jballerina-tools-${ballerinaLangVersion}" into ballerinaDist + duplicatesStrategy = DuplicatesStrategy.EXCLUDE /* Standard Libraries */ configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> @@ -109,7 +110,7 @@ clean { jar { enabled = false - dependsOn(shadowJar { classifier = null }) + dependsOn(shadowJar { archiveClassifier = null }) } shadowJar { @@ -124,7 +125,6 @@ shadowJar { include(dependency('io.swagger.core.v3:swagger-models')) include(dependency('io.swagger.parser.v3:swagger-parser')) include(dependency('io.swagger.parser.v3:swagger-parser-core')) - include(dependency('io.swagger.parser.v3:swagger-parser-v2-converter')) include(dependency('io.swagger.parser.v3:swagger-parser-v3')) exclude('META-INF/*.SF') exclude('META-INF/*.DSA') diff --git a/openapi-validator/src/main/java/io/ballerina/openapi/validator/Constants.java b/openapi-validator/src/main/java/io/ballerina/openapi/validator/Constants.java index 6deb01e9f..04b27c55d 100644 --- a/openapi-validator/src/main/java/io/ballerina/openapi/validator/Constants.java +++ b/openapi-validator/src/main/java/io/ballerina/openapi/validator/Constants.java @@ -79,6 +79,8 @@ public class Constants { Map httpCodes = new HashMap<>(); httpCodes.put("Continue", "100"); httpCodes.put("SwitchingProtocols", "101"); + httpCodes.put("Processing", "102"); + httpCodes.put("EarlyHints", "103"); httpCodes.put("Ok", "200"); httpCodes.put("Created", "201"); httpCodes.put("Accepted", "202"); @@ -86,6 +88,9 @@ public class Constants { httpCodes.put("NoContent", "204"); httpCodes.put("RestContent", "205"); httpCodes.put("PartialContent", "206"); + httpCodes.put("MultiStatus", "207"); + httpCodes.put("AlreadyReported", "208"); + httpCodes.put("IMUsed", "226"); httpCodes.put("MultipleChoices", "300"); httpCodes.put("MovedPermanently", "301"); httpCodes.put("Found", "302"); @@ -112,15 +117,29 @@ public class Constants { httpCodes.put("UnsupportedMediaType", "415"); httpCodes.put("RangeNotSatisfiable", "416"); httpCodes.put("ExpectationFailed", "417"); + httpCodes.put("MisdirectedRequest", "421"); + httpCodes.put("UnprocessableEntity", "422"); + httpCodes.put("Locked", "423"); + httpCodes.put("FailedDependency", "424"); + httpCodes.put("TooEarly", "425"); httpCodes.put("UpgradeRequired", "426"); + httpCodes.put("PreconditionRequired", "428"); httpCodes.put("TooManyRequests", "429"); httpCodes.put("RequestHeaderFieldsTooLarge", "431"); + httpCodes.put("UnavailableDueToLegalReasons", "451"); httpCodes.put("InternalServerError", "500"); httpCodes.put("NotImplemented", "501"); httpCodes.put("BadGateway", "502"); httpCodes.put("ServiceUnavailable", "503"); httpCodes.put("GatewayTimeOut", "504"); httpCodes.put("HttpVersionNotSupported", "505"); + httpCodes.put("VariantAlsoNegotiates", "506"); + httpCodes.put("InsufficientStorage", "507"); + httpCodes.put("LoopDetected", "508"); + httpCodes.put("NotExtended", "510"); + httpCodes.put("NetworkAuthenticationRequired", "511"); + httpCodes.put("NetworkAuthorizationRequired", "511"); //This status code was added since it is deprecated. + // TODO: remove this after fixing https://github.com/ballerina-platform/ballerina-standard-library/issues/4245 HTTP_CODES = Collections.unmodifiableMap(httpCodes); } public static final String HTTP_200 = "200"; diff --git a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ReturnTypeValidator.java b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ReturnTypeValidator.java index 9b7188d35..42b60b44f 100644 --- a/openapi-validator/src/main/java/io/ballerina/openapi/validator/ReturnTypeValidator.java +++ b/openapi-validator/src/main/java/io/ballerina/openapi/validator/ReturnTypeValidator.java @@ -219,7 +219,7 @@ private void validateSimpleNameReference(SimpleNameReferenceNode simpleRefNode, } } if (!isHttp) { - // validate normal Record status code 200 and application json + // validate normal Record status code 200 and application json , customized json if (responses.containsKey(HTTP_200)) { // record validation ApiResponse apiResponse = responses.get(HTTP_200); @@ -227,7 +227,18 @@ private void validateSimpleNameReference(SimpleNameReferenceNode simpleRefNode, MediaType oasMType = content.get(APPLICATION_JSON); balStatusCodes.put(HTTP_200, simpleRefNode); fillMediaTypes(HTTP_200, APPLICATION_JSON); - if (oasMType.getSchema() != null && oasMType.getSchema().get$ref() != null) { + //TODO: handle customized mediaType in ballerina service return and request body + /** + *
+                         * @openapi:ServiceInfo {
+                         *    contract: "snowpeak_openapi.yaml"}
+                         * @http:ServiceConfig { mediaTypeSubtypePrefix: "vnd.snowpeak.resort" }
+                         * service /snowpeak on new http:Listener(9090) {}
+                         * 
+ * issue: https://github.com/ballerina-platform/openapi-tools/issues/1044 + */ + if (oasMType != null && oasMType.getSchema() != null && + oasMType.getSchema().get$ref() != null) { Optional schemaName = extractReferenceType(oasMType.getSchema().get$ref()); if (schemaName.isEmpty()) { return; diff --git a/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/PreValidationTests.java b/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/PreValidationTests.java index 5af6b2e22..830c49b90 100644 --- a/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/PreValidationTests.java +++ b/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/PreValidationTests.java @@ -36,12 +36,17 @@ public class PreValidationTests { private static final Path RES_DIR = Paths.get("src/test/resources/pre-processing") .toAbsolutePath(); - @Test(description = "Annotation with non http service") + + // TODO: enable after releasing graphql with latest master + @Test(description = "Annotation with non http service", enabled = false) public void nonHttpService() { Path path = RES_DIR.resolve("non_http.bal"); Project project = getProject(path); DiagnosticResult diagnostic = getCompilation(project); - Assert.assertEquals(getDiagnostics(diagnostic).length, 0); + boolean isOpenapi = diagnostic.diagnostics().stream() + .anyMatch(d -> (d.properties().stream() + .anyMatch(p -> p.value().toString().contains("openapi")))); + Assert.assertFalse(isOpenapi); } @Test(description = "Given ballerina file has compilation issue") @@ -91,6 +96,16 @@ public void validatorTurnOff() { DiagnosticResult diagnostic = getCompilation(project); Object[] errors = diagnostic.diagnostics().stream().filter(d -> DiagnosticSeverity.WARNING == d.diagnosticInfo().severity()).toArray(); - Assert.assertEquals(errors.length, 5); + Assert.assertEquals(errors.length, 3); + String typeMismatch = "WARNING [multiple_services.bal:(5:10,5:18)] implementation type does not match with" + + " OpenAPI contract type (expected 'string', found 'int') for the field 'userName' of type 'User'."; + String unimplementedStatusCode = "WARNING [multiple_services.bal:(18:6,19:7)] undefined status code(s) " + + "'[500]' for return type in the counterpart Ballerina service resource (method: 'post', " + + "path: '/pets')."; + String undocumentedStatusCode = "WARNING [multiple_services.bal:(18:6,19:7)] missing implementation for " + + "return code(s) '[200]' in the counterpart Ballerina service resource (method: 'post', path: '/pets')."; + Assert.assertTrue(errors[0].toString().contains(typeMismatch)); + Assert.assertTrue(errors[1].toString().contains(unimplementedStatusCode)); + Assert.assertTrue(errors[2].toString().contains(undocumentedStatusCode)); } } diff --git a/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/ReturnTypeValidationTests.java b/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/ReturnTypeValidationTests.java index 64d648c61..226fb7ef8 100644 --- a/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/ReturnTypeValidationTests.java +++ b/openapi-validator/src/test/java/io/ballerina/openapi/validator/tests/ReturnTypeValidationTests.java @@ -233,4 +233,13 @@ public void handleModuleLevelQualifierRecord() { // TODO: res:ResRecord } + @Test(description = "Test for avoid the tool breaking from NPE when mediaType has customized prefix") + public void avoidCustomizedMediaType() { + Path path = RES_DIR.resolve("customized_mediaType.bal"); + Project project = getProject(path); + DiagnosticResult diagnostic = getCompilation(project); + Object[] errors = getDiagnostics(diagnostic); + Assert.assertEquals(errors.length, 0); + } + } diff --git a/openapi-validator/src/test/resources/pre-processing/multiple_services.bal b/openapi-validator/src/test/resources/pre-processing/multiple_services.bal index 0fc9dc860..03cc8f6e5 100644 --- a/openapi-validator/src/test/resources/pre-processing/multiple_services.bal +++ b/openapi-validator/src/test/resources/pre-processing/multiple_services.bal @@ -1,7 +1,7 @@ import ballerina/http; import ballerina/openapi; -type User record { +public type User record { int userName; string firstName?; string lastName?; diff --git a/openapi-validator/src/test/resources/return/customized_mediaType.bal b/openapi-validator/src/test/resources/return/customized_mediaType.bal new file mode 100644 index 000000000..27975e29b --- /dev/null +++ b/openapi-validator/src/test/resources/return/customized_mediaType.bal @@ -0,0 +1,15 @@ +import ballerina/openapi; +import ballerina/http; + +listener http:Listener ep0 = new (9090, config = {host: "localhost"}); + +@openapi:ServiceInfo{ + contract: "customized_mediaType.yaml", + failOnErrors: false +} +@http:ServiceConfig { mediaTypeSubtypePrefix: "vnd.snowpeak.reservation"} +service /v4 on ep0 { + resource function post pet/[string id](@http:Payload string payload) returns string { + return "test"; + } +} diff --git a/openapi-validator/src/test/resources/return/customized_mediaType.yaml b/openapi-validator/src/test/resources/return/customized_mediaType.yaml new file mode 100644 index 000000000..475e3d231 --- /dev/null +++ b/openapi-validator/src/test/resources/return/customized_mediaType.yaml @@ -0,0 +1,31 @@ +openapi: 3.0.1 +info: + title: V4 + version: 0.1.0 +servers: + - url: "{server}:{port}/v4" + variables: + server: + default: http://localhost + port: + default: "9090" +paths: + /pet/{id}: + post: + operationId: operation/pet + parameters: + - name: id + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + "application/json": + schema: + type: string + responses: + "200": + description: Accepted +components: {} diff --git a/settings.gradle b/settings.gradle index 4839083d6..8945be715 100644 --- a/settings.gradle +++ b/settings.gradle @@ -15,10 +15,10 @@ * */ plugins { - id "com.gradle.enterprise" version "3.5" + id "com.gradle.enterprise" version "3.13.2" } rootProject.name = 'openapi-tools' -include(':config:checkstyle') +include(':checkstyle') include(':module-ballerina-openapi') include(':openapi-bal-service') include(':openapi-build-extension') @@ -29,6 +29,7 @@ include(':openapi-extension') include(':openapi-extension-tests') include(':openapi-integration-tests') //include(':openapi-tests') +project(':checkstyle').projectDir = file("config${File.separator}checkstyle") gradleEnterprise { buildScan { @@ -37,4 +38,6 @@ gradleEnterprise { } } include 'openapi-build-extension' +include 'openapi-core' +//include 'openapi-client-idl-plugin' diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml index feaced49d..e5f90ecf4 100644 --- a/spotbugs-exclude.xml +++ b/spotbugs-exclude.xml @@ -16,4 +16,7 @@ ~ under the License. --> + + +