Setup a new project - mumayank/Rest-Api-Documentation GitHub Wiki
MySQL
CREATE DATABASE XXX;
CREATE USER 'x'@'localhost'
IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES
ON *.*
TO 'x'@'localhost';
FLUSH PRIVILEGES;
New spring boot project
- Go to start.spring.io
- Select dependencies:
Web
,MySQL
,JPA
- Download zip
- Extract zip
- Import extracted project into IDE
- Run
Application
class
application.properties file:
spring.datasource.username=x
spring.datasource.password=y
spring.datasource.url=jdbc:mysql://localhost:3306/xyz
spring.jpa.hibernate.ddl-auto=update
FeatureApi file:
@RestController
@RequestMapping("feature") // http://localhost:8080/users
public class FeatureApi {
@GetMapping
public String getX() {
return "";
}
// sub calls:
@PostMapping
@RequestMapping("/get")
fun getUser(@RequestBody userGetRequest: UserGetRequest): UserGetResponse? {
// some code
}
// Post, Put, Delete
}
- Sending response as Object -> Use POJO
- Receiving response as Object -> Use POJO and @RequestBody as:
@PostMapping
public String createEmployee(@RequestBody EmployeeCreateRequest employeeCreateRequest) {
//
}
Entity class
@Entity(name="users")
public class UserEntity {
@Id
@GeneratedValue
private long id;
@Column(nullable=false, length=100, unique = true)
private String email;
@Column(length = 80)
private String name;
@Column
private String password;
// getters and setters
}
Repository class
@Repository
public interface UserRepository extends CrudRepository<UserEntity, Long> {
UserEntity findByEmail(String email); // define custom methods like this. No need to define them fully.
}
Using repository class
(generally in API class)
Wherever you want to use repository (generally your API class), define on class top:
@Autowired
XxxRepository xxxRepository;
Throw custom exception
throw Exception("Invalid request. Please provide email id.")