Spring Farmework
Spring Farmework
2. Add Dependencies
In the pom.xml (for Maven) or build.gradle (for Gradle) file, ensure you have the
following dependencies for developing a REST API:
Spring Web: Provides the necessary components for building web applications and
RESTful APIs.
Spring Data JPA (optional): For database interaction (if you're using a relational
database like MySQL, PostgreSQL, etc.).
Spring Boot Starter Test: For unit and integration testing.
Spring Security (optional): For adding authentication and authorization mechanisms.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name); // Custom query method
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.createUser(user); // Create user with the given id
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id); // Assuming delete logic is implemented in
service
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException
ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUsers() throws Exception {
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("John Doe"));
}
}
9. Running the Application
To run the Spring Boot application, simply use the main method, which uses
SpringApplication.run(). This will start the embedded server (e.g., Tomcat).
Example:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
-----------------------------------------------------
Stateless Communication:
REST APIs are stateless, meaning each request from a client to a server must
contain all the information needed to understand and process the request.
The server does not store any state about the client session.
This simplifies scaling and enhances reliability since each request is independent.
HTTP Methods:
REST APIs use standard HTTP methods to perform operations on resources. Each method
corresponds to a CRUD (Create, Read, Update, Delete) action:
GET: Retrieve data from the server (Read).
POST: Submit data to the server (Create).
PUT: Update existing data on the server (Update).
DELETE: Remove data from the server (Delete).
Example: GET /api/users might retrieve a list of users, while POST /api/users would
create a new user.
Resource-Based Architecture:
REST APIs commonly use JSON (JavaScript Object Notation) as the data format due to
its readability and lightweight nature, though XML is also supported.
JSON has become the standard for REST APIs because it’s easy to parse and works
well with JavaScript and other languages.
REST APIs use HTTP status codes to indicate the result of the request, making it
easier for clients to understand the outcome.
200 OK: The request was successful.
201 Created: A resource was successfully created (typically in response to a POST
request).
400 Bad Request: The server couldn’t understand the request, likely due to invalid
input.
401 Unauthorized: The request requires authentication.
404 Not Found: The requested resource was not found.
500 Internal Server Error: A generic error indicating something went wrong on the
server.
Create a User:
POST /api/users with JSON body { "name": "John Doe", "email": "[email protected]" }
Response: 201 Created with the new user details.
Retrieve a User:
GET /api/users/123
Response: 200 OK with JSON body { "id": 123, "name": "John Doe", "email":
"[email protected]" }
Update a User:
Delete a User:
DELETE /api/users/123
Response: 204 No Content