├── .gitignore ├── Dockerfile ├── README.md ├── build.gradle.kts ├── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts ├── src ├── main │ ├── kotlin │ │ └── programmer │ │ │ └── zaman │ │ │ └── now │ │ │ └── kotlin │ │ │ └── restful │ │ │ ├── KotlinRestfulApiApplication.kt │ │ │ ├── auth │ │ │ ├── ApiKeyConfiguration.kt │ │ │ └── ApiKeyInterceptor.kt │ │ │ ├── config │ │ │ └── ApiKeySeeder.kt │ │ │ ├── controller │ │ │ ├── ErrorController.kt │ │ │ └── ProductController.kt │ │ │ ├── entity │ │ │ ├── ApiKey.kt │ │ │ └── Product.kt │ │ │ ├── error │ │ │ ├── NotFoundException.kt │ │ │ └── UnauthorizedException.kt │ │ │ ├── model │ │ │ ├── CreateProductRequest.kt │ │ │ ├── ListProductRequest.kt │ │ │ ├── ProductResponse.kt │ │ │ ├── UpdateProductRequest.kt │ │ │ └── WebResponse.kt │ │ │ ├── repository │ │ │ ├── ApiKeyRepository.kt │ │ │ └── ProductRepository.kt │ │ │ ├── service │ │ │ ├── ProductService.kt │ │ │ └── impl │ │ │ │ └── ProductServiceImpl.kt │ │ │ └── validation │ │ │ └── ValidationUtil.kt │ └── resources │ │ └── application.properties └── test │ └── kotlin │ └── programmer │ └── zaman │ └── now │ └── kotlin │ └── restful │ └── KotlinRestfulApiApplicationTests.kt ├── system-design.puml └── test.http /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | .DS_Store 8 | .idea 9 | 10 | ### STS ### 11 | .apt_generated 12 | .classpath 13 | .factorypath 14 | .project 15 | .settings 16 | .springBeans 17 | .sts4-cache 18 | 19 | ### IntelliJ IDEA ### 20 | .idea 21 | *.iws 22 | *.iml 23 | *.ipr 24 | out/ 25 | !**/src/main/**/out/ 26 | !**/src/test/**/out/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ 37 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-alpine 2 | 3 | COPY build/libs/kotlin-restful-api-0.0.1-SNAPSHOT.jar /app/application.jar 4 | 5 | CMD ["java", "-jar", "/app/application.jar"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # API Spec 2 | 3 | ## Authentication 4 | 5 | All API must use this authentication 6 | 7 | Request : 8 | - Header : 9 | - X-Api-Key : "your secret api key" 10 | 11 | ## Create Product 12 | 13 | Request : 14 | - Method : POST 15 | - Endpoint : `/api/products` 16 | - Header : 17 | - Content-Type: application/json 18 | - Accept: application/json 19 | - Body : 20 | 21 | ```json 22 | { 23 | "id" : "string, unique", 24 | "name" : "string", 25 | "price" : "long", 26 | "quantity" : "integer" 27 | } 28 | ``` 29 | 30 | Response : 31 | 32 | ```json 33 | { 34 | "code" : "number", 35 | "status" : "string", 36 | "data" : { 37 | "id" : "string, unique", 38 | "name" : "string", 39 | "price" : "long", 40 | "quantity" : "integer", 41 | "createdAt" : "date", 42 | "updatedAt" : "date" 43 | } 44 | } 45 | ``` 46 | 47 | ## Get Product 48 | 49 | Request : 50 | - Method : GET 51 | - Endpoint : `/api/products/{id_product}` 52 | - Header : 53 | - Accept: application/json 54 | 55 | Response : 56 | 57 | ```json 58 | { 59 | "code" : "number", 60 | "status" : "string", 61 | "data" : { 62 | "id" : "string, unique", 63 | "name" : "string", 64 | "price" : "long", 65 | "quantity" : "integer", 66 | "createdAt" : "date", 67 | "updatedAt" : "date" 68 | } 69 | } 70 | ``` 71 | 72 | ## Update Product 73 | 74 | Request : 75 | - Method : PUT 76 | - Endpoint : `/api/products/{id_product}` 77 | - Header : 78 | - Content-Type: application/json 79 | - Accept: application/json 80 | - Body : 81 | 82 | ```json 83 | { 84 | "name" : "string", 85 | "price" : "long", 86 | "quantity" : "integer" 87 | } 88 | ``` 89 | 90 | Response : 91 | 92 | ```json 93 | { 94 | "code" : "number", 95 | "status" : "string", 96 | "data" : { 97 | "id" : "string, unique", 98 | "name" : "string", 99 | "price" : "long", 100 | "quantity" : "integer", 101 | "createdAt" : "date", 102 | "updatedAt" : "date" 103 | } 104 | } 105 | ``` 106 | 107 | ## List Product 108 | 109 | Request : 110 | - Method : GET 111 | - Endpoint : `/api/products` 112 | - Header : 113 | - Accept: application/json 114 | - Query Param : 115 | - size : number, 116 | - page : number 117 | 118 | Response : 119 | 120 | ```json 121 | { 122 | "code" : "number", 123 | "status" : "string", 124 | "data" : [ 125 | { 126 | "id" : "string, unique", 127 | "name" : "string", 128 | "price" : "long", 129 | "quantity" : "integer", 130 | "createdAt" : "date", 131 | "updatedAt" : "date" 132 | }, 133 | { 134 | "id" : "string, unique", 135 | "name" : "string", 136 | "price" : "long", 137 | "quantity" : "integer", 138 | "createdAt" : "date", 139 | "updatedAt" : "date" 140 | } 141 | ] 142 | } 143 | ``` 144 | 145 | ## Delete Product 146 | 147 | Request : 148 | - Method : DELETE 149 | - Endpoint : `/api/products/{id_product}` 150 | - Header : 151 | - Accept: application/json 152 | 153 | Response : 154 | 155 | ```json 156 | { 157 | "code" : "number", 158 | "status" : "string" 159 | } 160 | ``` -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.3.4.RELEASE" 5 | id("io.spring.dependency-management") version "1.0.10.RELEASE" 6 | kotlin("jvm") version "1.3.72" 7 | kotlin("plugin.spring") version "1.3.72" 8 | kotlin("plugin.jpa") version "1.3.72" 9 | } 10 | 11 | group = "programmer-zaman-now" 12 | version = "0.0.1-SNAPSHOT" 13 | java.sourceCompatibility = JavaVersion.VERSION_1_8 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 21 | implementation("org.springframework.boot:spring-boot-starter-web") 22 | implementation("org.springframework.boot:spring-boot-starter-validation") 23 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 24 | implementation("org.jetbrains.kotlin:kotlin-reflect") 25 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 26 | runtimeOnly("org.postgresql:postgresql") 27 | testImplementation("org.springframework.boot:spring-boot-starter-test") { 28 | exclude(group = "org.junit.vintage", module = "junit-vintage-engine") 29 | } 30 | } 31 | 32 | tasks.withType { 33 | useJUnitPlatform() 34 | } 35 | 36 | tasks.withType { 37 | kotlinOptions { 38 | freeCompilerArgs = listOf("-Xjsr305=strict") 39 | jvmTarget = "1.8" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.5' 2 | 3 | services: 4 | kotlin-restful-api: 5 | container_name: kotlin-restful-api 6 | image: kotlin-restful-api:0.0.1 7 | ports: 8 | - 8080:8080 9 | environment: 10 | DATABASE_USERNAME: kotlin 11 | DATABASE_PASSWORD: kotlin 12 | DATABASE_URL: jdbc:postgresql://kotlin-restful-api-postgres:5432/restful-api 13 | kotlin-restful-api-postgres: 14 | container_name: "kotlin-restful-api-postgres" 15 | image: postgres:12-alpine 16 | ports: 17 | - 5432:5432 18 | environment: 19 | POSTGRES_PASSWORD: kotlin 20 | POSTGRES_USER: kotlin 21 | POSTGRES_DB: restful-api -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ProgrammerZamanNow/kotlin-restful-api/cacc1d10d3d8aec768732394507a86868fa2bae7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-restful-api" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/KotlinRestfulApiApplication.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class KotlinRestfulApiApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/auth/ApiKeyConfiguration.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.auth 2 | 3 | import org.springframework.stereotype.Component 4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer 6 | 7 | @Component 8 | class ApiKeyConfiguration(val apiKeyInterceptor: ApiKeyInterceptor) : WebMvcConfigurer{ 9 | 10 | override fun addInterceptors(registry: InterceptorRegistry) { 11 | super.addInterceptors(registry) 12 | 13 | registry.addWebRequestInterceptor(apiKeyInterceptor) 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/auth/ApiKeyInterceptor.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.auth 2 | 3 | import org.springframework.stereotype.Component 4 | import org.springframework.ui.ModelMap 5 | import org.springframework.web.context.request.WebRequest 6 | import org.springframework.web.context.request.WebRequestInterceptor 7 | import programmer.zaman.now.kotlin.restful.error.UnauthorizedException 8 | import programmer.zaman.now.kotlin.restful.repository.ApiKeyRepository 9 | import java.lang.Exception 10 | 11 | @Component 12 | class ApiKeyInterceptor(val apiKeyRepository: ApiKeyRepository) : WebRequestInterceptor { 13 | 14 | override fun preHandle(request: WebRequest) { 15 | val apiKey = request.getHeader("X-Api-Key") 16 | if (apiKey == null) { 17 | throw UnauthorizedException() 18 | } 19 | 20 | if (!apiKeyRepository.existsById(apiKey)) { 21 | throw UnauthorizedException() 22 | } 23 | 24 | // valid 25 | } 26 | 27 | override fun postHandle(request: WebRequest, model: ModelMap?) { 28 | // nothing 29 | } 30 | 31 | override fun afterCompletion(request: WebRequest, ex: Exception?) { 32 | // nothing 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/config/ApiKeySeeder.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.config 2 | 3 | import org.springframework.boot.ApplicationArguments 4 | import org.springframework.boot.ApplicationRunner 5 | import org.springframework.stereotype.Component 6 | import programmer.zaman.now.kotlin.restful.entity.ApiKey 7 | import programmer.zaman.now.kotlin.restful.repository.ApiKeyRepository 8 | 9 | @Component 10 | class ApiKeySeeder(val apiKeyRepository: ApiKeyRepository) : ApplicationRunner { 11 | 12 | val apiKey = "SECRET" 13 | 14 | override fun run(args: ApplicationArguments?) { 15 | if (!apiKeyRepository.existsById(apiKey)) { 16 | val entity = ApiKey(id = apiKey) 17 | apiKeyRepository.save(entity) 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/controller/ErrorController.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.controller 2 | 3 | import org.springframework.http.HttpStatus 4 | import org.springframework.web.bind.annotation.ExceptionHandler 5 | import org.springframework.web.bind.annotation.ResponseStatus 6 | import org.springframework.web.bind.annotation.RestControllerAdvice 7 | import programmer.zaman.now.kotlin.restful.error.NotFoundException 8 | import programmer.zaman.now.kotlin.restful.error.UnauthorizedException 9 | import programmer.zaman.now.kotlin.restful.model.WebResponse 10 | import javax.validation.ConstraintViolationException 11 | 12 | @RestControllerAdvice 13 | class ErrorController { 14 | 15 | @ResponseStatus(HttpStatus.BAD_REQUEST) 16 | @ExceptionHandler(value = [ConstraintViolationException::class]) 17 | fun validationHandler(constraintViolationException: ConstraintViolationException): WebResponse { 18 | return WebResponse( 19 | code = 400, 20 | status = "BAD REQUEST", 21 | data = constraintViolationException.message!! 22 | ) 23 | } 24 | 25 | @ResponseStatus(HttpStatus.NOT_FOUND) 26 | @ExceptionHandler(value = [NotFoundException::class]) 27 | fun notFound(notfoundException: NotFoundException): WebResponse { 28 | return WebResponse( 29 | code = 404, 30 | status = "NOT FOUND", 31 | data = "Not Found" 32 | ) 33 | } 34 | 35 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 36 | @ExceptionHandler(value = [UnauthorizedException::class]) 37 | fun unauthorized(unauthorizedException: UnauthorizedException): WebResponse { 38 | return WebResponse( 39 | code = 401, 40 | status = "UNAUTHORIZED", 41 | data = "Please put your X-Api-Key" 42 | ) 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/controller/ProductController.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.controller 2 | 3 | import org.springframework.web.bind.annotation.* 4 | import programmer.zaman.now.kotlin.restful.model.* 5 | import programmer.zaman.now.kotlin.restful.service.ProductService 6 | 7 | @RestController 8 | class ProductController(val productService: ProductService) { 9 | 10 | @PostMapping( 11 | value = ["/api/products"], 12 | produces = ["application/json"], 13 | consumes = ["application/json"] 14 | ) 15 | fun createProduct(@RequestBody body: CreateProductRequest): WebResponse { 16 | val productResponse = productService.create(body) 17 | return WebResponse( 18 | code = 200, 19 | status = "OK", 20 | data = productResponse 21 | ) 22 | } 23 | 24 | @GetMapping( 25 | value = ["/api/products/{idProduct}"], 26 | produces = ["application/json"] 27 | ) 28 | fun getProduct(@PathVariable("idProduct") id: String): WebResponse { 29 | val productResponse = productService.get(id) 30 | return WebResponse( 31 | code = 200, 32 | status = "OK", 33 | data = productResponse 34 | ) 35 | } 36 | 37 | @PutMapping( 38 | value = ["/api/products/{idProduct}"], 39 | produces = ["application/json"], 40 | consumes = ["application/json"] 41 | ) 42 | fun updateProduct(@PathVariable("idProduct") id: String, 43 | @RequestBody updateProductRequest: UpdateProductRequest): WebResponse { 44 | val productResponse = productService.update(id, updateProductRequest) 45 | return WebResponse( 46 | code = 200, 47 | status = "OK", 48 | data = productResponse 49 | ) 50 | } 51 | 52 | @DeleteMapping( 53 | value = ["/api/products/{idProduct}"], 54 | produces = ["application/json"] 55 | ) 56 | fun deleteProduct(@PathVariable("idProduct") id: String): WebResponse { 57 | productService.delete(id) 58 | return WebResponse( 59 | code = 200, 60 | status = "OK", 61 | data = id 62 | ) 63 | } 64 | 65 | @GetMapping( 66 | value = ["/api/products"], 67 | produces = ["application/json"] 68 | ) 69 | fun listProducts(@RequestParam(value = "size", defaultValue = "10") size: Int, 70 | @RequestParam(value = "page", defaultValue = "0") page: Int): WebResponse> { 71 | val request = ListProductRequest(page = page, size = size) 72 | val responses = productService.list(request) 73 | return WebResponse( 74 | code = 200, 75 | status = "OK", 76 | data = responses 77 | ) 78 | } 79 | 80 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/entity/ApiKey.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.entity 2 | 3 | import javax.persistence.Entity 4 | import javax.persistence.Id 5 | import javax.persistence.Table 6 | 7 | @Entity 8 | @Table(name = "api_keys") 9 | data class ApiKey( 10 | 11 | @Id 12 | val id: String 13 | 14 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/entity/Product.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.entity 2 | 3 | import java.util.* 4 | import javax.persistence.Column 5 | import javax.persistence.Entity 6 | import javax.persistence.Id 7 | import javax.persistence.Table 8 | 9 | @Entity 10 | @Table(name = "products") 11 | data class Product( 12 | 13 | @Id 14 | val id: String, 15 | 16 | @Column(name = "name") 17 | var name: String, 18 | 19 | @Column(name = "price") 20 | var price: Long, 21 | 22 | @Column(name = "quantity") 23 | var quantity: Int, 24 | 25 | @Column(name = "created_at") 26 | var createdAt: Date, 27 | 28 | @Column(name = "updated_at") 29 | var updatedAt: Date? 30 | 31 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/error/NotFoundException.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.error 2 | 3 | class NotFoundException : Exception() { 4 | 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/error/UnauthorizedException.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.error 2 | 3 | class UnauthorizedException : Exception() { 4 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/model/CreateProductRequest.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.model 2 | 3 | import javax.validation.constraints.Min 4 | import javax.validation.constraints.NotBlank 5 | import javax.validation.constraints.NotNull 6 | 7 | data class CreateProductRequest( 8 | 9 | @field:NotBlank 10 | val id: String?, 11 | 12 | @field:NotBlank 13 | val name: String?, 14 | 15 | @field:NotNull 16 | @field:Min(value = 1) 17 | val price: Long?, 18 | 19 | @field:NotNull 20 | @field:Min(value = 0) 21 | val quantity: Int? 22 | 23 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/model/ListProductRequest.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.model 2 | 3 | data class ListProductRequest( 4 | 5 | val page: Int, 6 | 7 | val size: Int 8 | 9 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/model/ProductResponse.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.model 2 | 3 | import java.util.* 4 | 5 | data class ProductResponse( 6 | 7 | val id: String, 8 | 9 | val name: String, 10 | 11 | val price: Long, 12 | 13 | val quantity: Int, 14 | 15 | val createdAt: Date, 16 | 17 | val updatedAt: Date? 18 | 19 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/model/UpdateProductRequest.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.model 2 | 3 | import javax.validation.constraints.Min 4 | import javax.validation.constraints.NotBlank 5 | import javax.validation.constraints.NotNull 6 | 7 | data class UpdateProductRequest( 8 | 9 | @field:NotBlank 10 | val name: String?, 11 | 12 | @field:NotNull 13 | @field:Min(1) 14 | val price: Long?, 15 | 16 | @field:NotNull 17 | @field:Min(0) 18 | val quantity: Int? 19 | 20 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/model/WebResponse.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.model 2 | 3 | data class WebResponse( 4 | 5 | val code: Int, 6 | 7 | val status: String, 8 | 9 | val data: T 10 | ) -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/repository/ApiKeyRepository.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.repository 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository 4 | import programmer.zaman.now.kotlin.restful.entity.ApiKey 5 | 6 | interface ApiKeyRepository : JpaRepository { 7 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/repository/ProductRepository.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.repository 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository 4 | import programmer.zaman.now.kotlin.restful.entity.Product 5 | 6 | interface ProductRepository : JpaRepository{ 7 | 8 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/service/ProductService.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.service 2 | 3 | import programmer.zaman.now.kotlin.restful.model.CreateProductRequest 4 | import programmer.zaman.now.kotlin.restful.model.ListProductRequest 5 | import programmer.zaman.now.kotlin.restful.model.ProductResponse 6 | import programmer.zaman.now.kotlin.restful.model.UpdateProductRequest 7 | 8 | interface ProductService { 9 | 10 | fun create(createProductRequest: CreateProductRequest): ProductResponse 11 | 12 | fun get(id: String): ProductResponse 13 | 14 | fun update(id: String, updateProductRequest: UpdateProductRequest): ProductResponse 15 | 16 | fun delete(id: String) 17 | 18 | fun list(listProductRequest: ListProductRequest): List 19 | 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/service/impl/ProductServiceImpl.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.service.impl 2 | 3 | import org.springframework.data.domain.PageRequest 4 | import org.springframework.data.repository.findByIdOrNull 5 | import org.springframework.stereotype.Service 6 | import programmer.zaman.now.kotlin.restful.entity.Product 7 | import programmer.zaman.now.kotlin.restful.error.NotFoundException 8 | import programmer.zaman.now.kotlin.restful.model.CreateProductRequest 9 | import programmer.zaman.now.kotlin.restful.model.ListProductRequest 10 | import programmer.zaman.now.kotlin.restful.model.ProductResponse 11 | import programmer.zaman.now.kotlin.restful.model.UpdateProductRequest 12 | import programmer.zaman.now.kotlin.restful.repository.ProductRepository 13 | import programmer.zaman.now.kotlin.restful.service.ProductService 14 | import programmer.zaman.now.kotlin.restful.validation.ValidationUtil 15 | import java.util.* 16 | import java.util.stream.Collectors 17 | 18 | @Service 19 | class ProductServiceImpl( 20 | val productRepository: ProductRepository, 21 | val validationUtil: ValidationUtil 22 | ) : ProductService { 23 | 24 | override fun create(createProductRequest: CreateProductRequest): ProductResponse { 25 | validationUtil.validate(createProductRequest) 26 | 27 | val product = Product( 28 | id = createProductRequest.id!!, 29 | name = createProductRequest.name!!, 30 | price = createProductRequest.price!!, 31 | quantity = createProductRequest.quantity!!, 32 | createdAt = Date(), 33 | updatedAt = null 34 | ) 35 | 36 | productRepository.save(product) 37 | 38 | return convertProductToProductResponse(product) 39 | } 40 | 41 | override fun get(id: String): ProductResponse { 42 | val product = findProductByIdOrThrowNotFound(id) 43 | return convertProductToProductResponse(product) 44 | } 45 | 46 | override fun update(id: String, updateProductRequest: UpdateProductRequest): ProductResponse { 47 | val product = findProductByIdOrThrowNotFound(id) 48 | 49 | validationUtil.validate(updateProductRequest) 50 | 51 | product.apply { 52 | name = updateProductRequest.name!! 53 | price = updateProductRequest.price!! 54 | quantity = updateProductRequest.quantity!! 55 | updatedAt = Date() 56 | } 57 | 58 | productRepository.save(product) 59 | 60 | return convertProductToProductResponse(product) 61 | } 62 | 63 | override fun delete(id: String) { 64 | val product = findProductByIdOrThrowNotFound(id) 65 | productRepository.delete(product) 66 | } 67 | 68 | override fun list(listProductRequest: ListProductRequest): List { 69 | val page = productRepository.findAll(PageRequest.of(listProductRequest.page, listProductRequest.size)) 70 | val products: List = page.get().collect(Collectors.toList()) 71 | return products.map { convertProductToProductResponse(it) } 72 | } 73 | 74 | private fun findProductByIdOrThrowNotFound(id: String): Product { 75 | val product = productRepository.findByIdOrNull(id) 76 | if (product == null) { 77 | throw NotFoundException() 78 | } else { 79 | return product; 80 | } 81 | } 82 | 83 | private fun convertProductToProductResponse(product: Product): ProductResponse { 84 | return ProductResponse( 85 | id = product.id, 86 | name = product.name, 87 | price = product.price, 88 | quantity = product.quantity, 89 | createdAt = product.createdAt, 90 | updatedAt = product.updatedAt 91 | ) 92 | } 93 | } -------------------------------------------------------------------------------- /src/main/kotlin/programmer/zaman/now/kotlin/restful/validation/ValidationUtil.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful.validation 2 | 3 | import org.springframework.stereotype.Component 4 | import javax.validation.ConstraintViolationException 5 | import javax.validation.Validator 6 | 7 | @Component 8 | class ValidationUtil(val validator: Validator) { 9 | 10 | fun validate(any: Any) { 11 | val result = validator.validate(any) 12 | if (result.size != 0) { 13 | throw ConstraintViolationException(result) 14 | } 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.username=${DATABASE_USERNAME:kotlin} 2 | spring.datasource.password=${DATABASE_PASSWORD:kotlin} 3 | spring.datasource.url=${DATABASE_URL:jdbc:postgresql://localhost:5432/restful-api} 4 | spring.jpa.hibernate.ddl-auto=update 5 | -------------------------------------------------------------------------------- /src/test/kotlin/programmer/zaman/now/kotlin/restful/KotlinRestfulApiApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package programmer.zaman.now.kotlin.restful 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class KotlinRestfulApiApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /system-design.puml: -------------------------------------------------------------------------------- 1 | @startuml 2 | 3 | actor "User" as user 4 | node "Kotlin RESTful API" { 5 | component "Controller" as controller 6 | component "Service" as service 7 | component "Repository" as repository 8 | } 9 | 10 | database "PostgreSQL" as database 11 | 12 | user <--> controller 13 | controller <--> service 14 | service <--> repository 15 | repository <--> database 16 | 17 | @enduml -------------------------------------------------------------------------------- /test.http: -------------------------------------------------------------------------------- 1 | ### Create product 2 | 3 | POST http://localhost:8080/api/products 4 | X-Api-Key: SECRET 5 | Content-Type: application/json 6 | Accept: application/json 7 | 8 | { 9 | "id" : "A0010", 10 | "name" : "Mac Book Pro 15", 11 | "price" : 30000000, 12 | "quantity" : 10 13 | } 14 | 15 | ### Create product invalid 16 | 17 | POST http://localhost:8080/api/products 18 | X-Api-Key: SECRET 19 | Content-Type: application/json 20 | Accept: application/json 21 | 22 | { 23 | "id" : "", 24 | "name" : "", 25 | "price" : 0, 26 | "quantity" : -10 27 | } 28 | 29 | ### Get product 30 | 31 | GET http://localhost:8080/api/products/A0001 32 | X-Api-Key: SECRET 33 | Accept: application/json 34 | 35 | ### Get product not found 36 | 37 | GET http://localhost:8080/api/products/SALAH 38 | X-Api-Key: SECRET 39 | Accept: application/json 40 | 41 | ### Update product 42 | 43 | PUT http://localhost:8080/api/products/A0001 44 | X-Api-Key: SECRET 45 | Content-Type: application/json 46 | Accept: application/json 47 | 48 | { 49 | "name" : "Apple Mac Book Pro 15 2020", 50 | "price" : 40000000, 51 | "quantity" : 100 52 | } 53 | 54 | ### Update product not found 55 | 56 | PUT http://localhost:8080/api/products/SALAH 57 | X-Api-Key: SECRET 58 | Content-Type: application/json 59 | Accept: application/json 60 | 61 | { 62 | "name" : "Apple Mac Book Pro 15 2020", 63 | "price" : 40000000, 64 | "quantity" : 100 65 | } 66 | 67 | ### Update product with invalid body 68 | 69 | PUT http://localhost:8080/api/products/A0001 70 | X-Api-Key: SECRET 71 | Content-Type: application/json 72 | Accept: application/json 73 | 74 | { 75 | "name" : "", 76 | "price" : 0, 77 | "quantity" : -10 78 | } 79 | 80 | ### Delete product 81 | 82 | DELETE http://localhost:8080/api/products/A0001 83 | X-Api-Key: SECRET 84 | Accept: application/json 85 | 86 | ### List products 87 | 88 | GET http://localhost:8080/api/products 89 | X-Api-Key: SECRET 90 | Accept: application/json 91 | 92 | ### List products with size parameter 93 | 94 | GET http://localhost:8080/api/products?size=5 95 | X-Api-Key: SECRET 96 | Accept: application/json 97 | 98 | ### List products with size and page parameter 99 | 100 | GET http://localhost:8080/api/products?size=5&page=1 101 | X-Api-Key: SECRET 102 | Accept: application/json --------------------------------------------------------------------------------