├── settings.gradle ├── Procfile ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ ├── java │ │ └── me │ │ │ └── dio │ │ │ ├── exception │ │ │ ├── NotFoundException.java │ │ │ ├── BusinessException.java │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── service │ │ │ ├── HeroService.java │ │ │ ├── CrudService.java │ │ │ └── impl │ │ │ │ └── HeroServiceImpl.java │ │ │ ├── repository │ │ │ └── HeroRepository.java │ │ │ ├── Application.java │ │ │ ├── model │ │ │ └── Hero.java │ │ │ └── controller │ │ │ └── HeroController.java │ └── resources │ │ ├── application-prd.yml │ │ └── application-dev.yml └── test │ └── java │ └── me │ └── dio │ └── ApplicationTests.java ├── .gitignore ├── LICENSE.md ├── gradlew.bat ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-boot-3-rest-api-template' 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java -jar build/libs/spring-boot-3-rest-api-template-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digitalinnovationone/spring-boot-3-rest-api-template/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/me/dio/exception/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package me.dio.exception; 2 | 3 | public class NotFoundException extends RuntimeException { 4 | 5 | private static final long serialVersionUID = 1L; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/me/dio/service/HeroService.java: -------------------------------------------------------------------------------- 1 | package me.dio.service; 2 | 3 | import me.dio.model.Hero; 4 | 5 | public interface HeroService extends CrudService { 6 | void increaseXp(Long id); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/resources/application-prd.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:postgresql://${RAILWAY_DB_HOST}:${RAILWAY_DB_PORT}/${RAILWAY_DB_NAME} 4 | username: ${RAILWAY_DB_USERNAME} 5 | password: ${RAILWAY_DB_PASSWORD} 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/test/java/me/dio/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package me.dio; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/me/dio/service/CrudService.java: -------------------------------------------------------------------------------- 1 | package me.dio.service; 2 | 3 | import java.util.List; 4 | 5 | public interface CrudService { 6 | List findAll(); 7 | T findById(ID id); 8 | T create(T entity); 9 | T update(ID id, T entity); 10 | void delete(ID id); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/me/dio/exception/BusinessException.java: -------------------------------------------------------------------------------- 1 | package me.dio.exception; 2 | 3 | public class BusinessException extends RuntimeException { 4 | 5 | private static final long serialVersionUID = 1L; 6 | 7 | public BusinessException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/me/dio/repository/HeroRepository.java: -------------------------------------------------------------------------------- 1 | package me.dio.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import me.dio.model.Hero; 7 | 8 | @Repository 9 | public interface HeroRepository extends JpaRepository { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:h2:mem:heroes 4 | username: rafa 5 | password: 6 | jpa: 7 | show-sql: true 8 | open-in-view: false 9 | hibernate: 10 | ddl-auto: update 11 | properties: 12 | hibernate: 13 | format_sql: true 14 | h2: 15 | console: 16 | enabled: true 17 | path: /h2-console 18 | settings: 19 | trace: false 20 | web-allow-others: false 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /src/main/java/me/dio/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package me.dio.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | 7 | import org.springframework.web.bind.annotation.RestControllerAdvice; 8 | 9 | @RestControllerAdvice 10 | public class GlobalExceptionHandler { 11 | 12 | @ExceptionHandler(BusinessException.class) 13 | public ResponseEntity handleBusinessException(BusinessException ex) { 14 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY); 15 | } 16 | 17 | @ExceptionHandler(NotFoundException.class) 18 | public ResponseEntity handleNoContentException() { 19 | return new ResponseEntity<>("Resource ID not found.", HttpStatus.NOT_FOUND); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/me/dio/Application.java: -------------------------------------------------------------------------------- 1 | package me.dio; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | import io.swagger.v3.oas.annotations.OpenAPIDefinition; 7 | import io.swagger.v3.oas.annotations.servers.Server; 8 | 9 | /** 10 | * Initializes our RESTful API. 11 | * 12 | *

13 | * The {@link OpenAPIDefinition} annotation was used to enable HTTPS in the Swagger UI. 14 | * For more details, see the following post on Stack Overflow: 15 | * https://stackoverflow.com/a/71132608/3072570 16 | *

17 | */ 18 | 19 | @OpenAPIDefinition(servers = {@Server(url = "/", description = "Default Server URL")}) 20 | @SpringBootApplication 21 | public class Application { 22 | public static void main(String[] args) { 23 | SpringApplication.run(Application.class, args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Camila Cavalcante 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /src/main/java/me/dio/model/Hero.java: -------------------------------------------------------------------------------- 1 | package me.dio.model; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.GenerationType; 6 | import jakarta.persistence.Id; 7 | import jakarta.persistence.Version; 8 | 9 | @Entity(name = "HEROES") 10 | public class Hero { 11 | 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private Long id; 15 | private String name; 16 | private int xp; 17 | /* 18 | * The version field is marked with the @Version annotation. This means JPA will 19 | * automatically take care of versioning for the Hero entity, which helps 20 | * prevent concurrent modification conflicts. 21 | */ 22 | @Version 23 | private int version; 24 | 25 | public Long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(Long id) { 30 | this.id = id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public int getXp() { 42 | return xp; 43 | } 44 | 45 | public void setXp(int xp) { 46 | this.xp = xp; 47 | } 48 | 49 | public int getVersion() { 50 | return version; 51 | } 52 | 53 | public void setVersion(int version) { 54 | this.version = version; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/me/dio/service/impl/HeroServiceImpl.java: -------------------------------------------------------------------------------- 1 | package me.dio.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Sort; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import me.dio.exception.BusinessException; 11 | import me.dio.exception.NotFoundException; 12 | import me.dio.model.Hero; 13 | import me.dio.repository.HeroRepository; 14 | import me.dio.service.HeroService; 15 | 16 | @Service 17 | @Transactional 18 | public class HeroServiceImpl implements HeroService { 19 | 20 | @Autowired 21 | private HeroRepository heroRepository; 22 | 23 | @Transactional(readOnly = true) 24 | public List findAll() { 25 | // DONE! Sort Heroes by "xp" descending. 26 | return this.heroRepository.findAll(Sort.by(Sort.Direction.DESC, "xp")); 27 | } 28 | 29 | @Transactional(readOnly = true) 30 | public Hero findById(Long id) { 31 | return this.heroRepository.findById(id).orElseThrow(NotFoundException::new); 32 | } 33 | 34 | public Hero create(Hero heroToCreate) { 35 | heroToCreate.setXp(0); 36 | return this.heroRepository.save(heroToCreate); 37 | } 38 | 39 | public Hero update(Long id, Hero heroToUpdate) { 40 | Hero dbHero = this.findById(id); 41 | if (!dbHero.getId().equals(heroToUpdate.getId())) { 42 | throw new BusinessException("Update IDs must be the same."); 43 | } 44 | // DONE! Make sure "xp" is not changed. In practice, only "name" can be changed. 45 | dbHero.setName(heroToUpdate.getName()); 46 | return this.heroRepository.save(dbHero); 47 | } 48 | 49 | public void delete(Long id) { 50 | Hero dbHero = this.findById(id); 51 | this.heroRepository.delete(dbHero); 52 | } 53 | 54 | public void increaseXp(Long id) { 55 | Hero dbHero = this.findById(id); 56 | dbHero.setXp(dbHero.getXp() + 2); 57 | heroRepository.save(dbHero); 58 | } 59 | } -------------------------------------------------------------------------------- /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% equ 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% equ 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 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /src/main/java/me/dio/controller/HeroController.java: -------------------------------------------------------------------------------- 1 | package me.dio.controller; 2 | 3 | import java.net.URI; 4 | import java.util.List; 5 | 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.DeleteMapping; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PatchMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.PutMapping; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RestController; 16 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 17 | 18 | import io.swagger.v3.oas.annotations.Operation; 19 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 20 | import io.swagger.v3.oas.annotations.responses.ApiResponses; 21 | import io.swagger.v3.oas.annotations.tags.Tag; 22 | import me.dio.model.Hero; 23 | import me.dio.service.HeroService; 24 | 25 | @RestController 26 | @RequestMapping("/heroes") 27 | @Tag(name = "Heroes Controller", description = "RESTful API for managing heroes.") 28 | public record HeroController(HeroService heroService) { 29 | 30 | @GetMapping 31 | @Operation(summary = "Get all heroes", description = "Get a list of all registered heroes") 32 | @ApiResponses(value = { 33 | @ApiResponse(responseCode = "200", description = "Successful operation") 34 | }) 35 | public ResponseEntity> findAll() { 36 | return ResponseEntity.ok(heroService.findAll()); 37 | } 38 | 39 | @GetMapping("/{id}") 40 | @Operation(summary = "Get a hero by ID", description = "Get a specific hero based on its ID") 41 | @ApiResponses(value = { 42 | @ApiResponse(responseCode = "200", description = "Successful operation"), 43 | @ApiResponse(responseCode = "404", description = "Hero not found") 44 | }) 45 | public ResponseEntity findById(@PathVariable Long id) { 46 | return ResponseEntity.ok(heroService.findById(id)); 47 | } 48 | 49 | @PostMapping 50 | @Operation(summary = "Create a new hero", description = "Create a new hero and returns the created hero") 51 | @ApiResponses(value = { 52 | @ApiResponse(responseCode = "201", description = "Hero created successfully"), 53 | @ApiResponse(responseCode = "422", description = "Invalid hero data provided") 54 | }) 55 | public ResponseEntity create(@RequestBody Hero hero) { 56 | // TODO: Create a DTO to avoid expose unnecessary Hero model attributes. 57 | Hero createdHero = heroService.create(hero); 58 | URI location = ServletUriComponentsBuilder.fromCurrentRequest() 59 | .path("/{id}") 60 | .buildAndExpand(createdHero.getId()) 61 | .toUri(); 62 | return ResponseEntity.created(location).body(createdHero); 63 | } 64 | 65 | @PutMapping("/{id}") 66 | @Operation(summary = "Update a hero", description = "Update an existing hero based on its ID") 67 | @ApiResponses(value = { 68 | @ApiResponse(responseCode = "200", description = "Hero updated successfully"), 69 | @ApiResponse(responseCode = "404", description = "Hero not found"), 70 | @ApiResponse(responseCode = "422", description = "Invalid hero data provided") 71 | }) 72 | public ResponseEntity update(@PathVariable Long id, @RequestBody Hero hero) { 73 | // TODO: Create a DTO to avoid expose unnecessary Hero model attributes. 74 | return ResponseEntity.ok(heroService.update(id, hero)); 75 | } 76 | 77 | @DeleteMapping("/{id}") 78 | @Operation(summary = "Delete a hero", description = "Delete an existing hero based on its ID") 79 | @ApiResponses(value = { 80 | @ApiResponse(responseCode = "204", description = "Hero deleted successfully"), 81 | @ApiResponse(responseCode = "404", description = "Hero not found") 82 | }) 83 | public ResponseEntity delete(@PathVariable Long id) { 84 | heroService.delete(id); 85 | return ResponseEntity.noContent().build(); 86 | } 87 | 88 | @PatchMapping("/{id}/up") 89 | @Operation(summary = "Increase hero XP", description = "Up XP to an existing hero based on its ID") 90 | @ApiResponses(value = { 91 | @ApiResponse(responseCode = "204", description = "Vote registered successfully"), 92 | @ApiResponse(responseCode = "404", description = "Hero not found") 93 | }) 94 | public ResponseEntity vote(@PathVariable Long id) { 95 | heroService.increaseXp(id); 96 | return ResponseEntity.noContent().build(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DIO Spring Boot RESTful API Template 2 | 3 | Welcome to the DIO Spring Boot RESTful API Template! This project serves as a foundational template for creating RESTful APIs using Spring Boot 3, Spring Data JPA, and OpenAPI (Swagger) for API documentation. We have utilized the power of Java 17, the latest LTS version of Java, to build this project. 4 | 5 | As an edtech company, DIO is committed to providing valuable resources for developers and this project is no exception. It stands as a quick start guide to jump-start your API development with the best practices embedded. 6 | 7 |

8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |

24 | 25 | ## Table of Contents 26 | 27 | - [Key Features](#key-features) 28 | - [Project Structure](#project-structure) 29 | - [Setup](#setup) 30 | - [Project Details](#project-details) 31 | - [API Usage (Swagger UI Documentation)](#api-usage-swagger-ui-documentation) 32 | - [Hosting on Railway.app](#hosting-on-railway) 33 | - [Contribution](#contribution) 34 | - [License](#license) 35 | - [Authors](#authors) 36 | 37 | ## Key Features: 38 | 39 | - **Java 17**: Leveraging the latest LTS version of Java, improving readability and efficiency. 40 | - **Spring Boot 3**: An upgraded version of Spring Boot, enhancing developer productivity with its auto-configuration 41 | feature. Generated using [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=3.1.1&packaging=jar&jvmVersion=17&groupId=me.dio&artifactId=spring-boot-3-rest-api-template&name=spring-boot-3-rest-api-template&description=DIO%20Spring%20Boot%20RESTful%20API%20Template&packageName=me.dio&dependencies=web,data-jpa,h2,postgresql). 42 | - **Spring Data JPA**: Simplifying the database access layer by reducing the boilerplate code. 43 | - **OpenAPI (Swagger)**: Integrated with OpenAPI 3, enabling seamless API documentation for better understanding and 44 | testing. 45 | 46 | ## Project Structure: 47 | 48 | The project is organized into several packages, each serving a specific purpose: 49 | 50 | - `controller`: This package contains our Rest Controllers. Here, we expose our endpoints, following the REST architectural style. DTOs are used in this layer to define the consumption interfaces appropriately, avoiding the exposure of unnecessary model attributes. 51 | 52 | - `exception`: define our custom exceptions and a global exception handler for dealing with Spring's exceptions. 53 | 54 | - `model`: where our entities are defined, using JPA (Jakarta) annotations for ORM with our SQL database. 55 | 56 | - `repository`: In this package, we handle data access using interfaces provided by Spring Data JPA. 57 | 58 | - `service`: where our business logic lives. Here we validate our data, handle business exceptions, and manage access to our SQL database through repositories. 59 | 60 | - `Application.java`: This is the main class to run our project. It initializes our Spring application and connects all the components together. 61 | 62 | Please note that this structure is a simple suggestion for educational purposes. Each developer is free to adapt and modify this structure according to their project needs and standards. 63 | 64 | ## Setup 65 | 66 | These instructions guide you through cloning the repository and starting the application in Unix or Windows environments, with the development profile enabled. 67 | 68 | 1. Clone the repository: git clone https://github.com/digitalinnovationone/spring-boot-3-rest-api-template.git 69 | 2. Start the application in the Unix environment: `./gradlew bootrun --args='--spring.profiles.active=dev'` 70 | 3. Start the application in the Windows environment: `gradle.bat bootrun --args='--spring.profiles.active=dev'` 71 | 72 | ## Project Details: 73 | 74 | The project focuses on a Heroes API as an example, which includes basic CRUD operations and gain experience (XP) system. It adheres to the best practices of RESTful principles, such as idempotent operations and the use of appropriate HTTP status codes. 75 | 76 | Exception handling is globally managed with a `@RestControllerAdvice` to ensure consistent handling of exceptions throughout the entire application. 77 | 78 | The project also includes the setup for an H2 database (an in-memory database) for testing purposes and development environment. For the production environment on Railway, PostgreSQL database is used. 79 | 80 | ## API Usage (Swagger UI Documentation) 81 | 82 | The API documentation can be found on Swagger UI. To view it, please visit: [Swagger UI](http://localhost:8080/swagger-ui.html). 83 | 84 | ## Hosting on Railway 85 | 86 | Both this project and your PostgreSQL database are hosted on [Railway.app](https://railway.app/). To access our demo application, visit: 87 | - Development Environment: [https://[your-public-domain]-dev.up.railway.app/swagger-ui.html](https://heroes-api-veni-dev.up.railway.app/swagger-ui.html) 88 | - Production Environment: [https://[your-public-domain]-prd.up.railway.app/swagger-ui.html](https://heroes-api-veni-prd.up.railway.app/swagger-ui.html) 89 | 90 | ## Contribution 91 | 92 | We welcome contributions! If you encounter any issues or have suggestions for improvements, don't hesitate to open an issue or submit a pull request. 93 | 94 | ## License 95 | 96 | This project is licensed under the MIT License. Please refer to the (LICENSE) file for details. 97 | 98 | ## Authors 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 |

Venilton FalvoJr

LinkedIn

Camila Cavalcante

LinkedIn

Rafa Skoberg

LinkedIn
107 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original 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 POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | --------------------------------------------------------------------------------