CodeWithAbdessamad

Rest Api

REST API

In this section, we’ll build a practical REST API application that demonstrates the full CRUD (Create, Read, Update, Delete) operations. This hands-on project will help you solidify your understanding of RESTful principles and implement a real-world application using Java. 🌟

Building a CRUD Application with Spring Boot

We’ll create a minimal Spring Boot project that provides a REST API for managing Person entities. This example uses Spring Data JPA with H2 for simplicity.

First, define a Person model:

<code class="language-java">package com.example.person;

<p>public class Person {</p>
<p>    private Long id;</p>
<p>    private String name;</p>
<p>    private int age;</p>

<p>    // Getters and setters</p>
<p>}</code>

Next, create a repository interface:

<code class="language-java">package com.example.person.repository;

<p>import com.example.person.Person;</p>
<p>import org.springframework.data.jpa.repository.JpaRepository;</p>

<p>public interface PersonRepository extends JpaRepository<Person, Long> {</p>
<p>}</code>

Now, implement the controller:

<code class="language-java">package com.example.person.controller;

<p>import com.example.person.Person;</p>
<p>import com.example.person.repository.PersonRepository;</p>
<p>import org.springframework.beans.factory.annotation.Autowired;</p>
<p>import org.springframework.http.ResponseEntity;</p>
<p>import org.springframework.web.bind.annotation.*;</p>
<p>import java.util.List;</p>

<p>@RestController</p>
<p>@RequestMapping("/api/persons")</p>
<p>public class PersonController {</p>

<p>    @Autowired</p>
<p>    private PersonRepository personRepository;</p>

<p>    @GetMapping</p>
<p>    public List<Person> getAllPersons() {</p>
<p>        return personRepository.findAll();</p>
<p>    }</p>

<p>    @PostMapping</p>
<p>    public Person createPerson(@RequestBody Person person) {</p>
<p>        return personRepository.save(person);</p>
<p>    }</p>

<p>    @GetMapping("/{id}")</p>
<p>    public Person getPersonById(@PathVariable Long id) {</p>
<p>        return personRepository.findById(id)</p>
<p>                .orElseThrow(() -> new RuntimeException("Person not found"));</p>
<p>    }</p>

<p>    @PutMapping("/{id}")</p>
<p>    public Person updatePerson(@PathVariable Long id, @RequestBody Person person) {</p>
<p>        person.setId(id);</p>
<p>        return personRepository.save(person);</p>
<p>    }</p>

<p>    @DeleteMapping("/{id}")</p>
<p>    public ResponseEntity<Void> deletePerson(@PathVariable Long id) {</p>
<p>        personRepository.deleteById(id);</p>
<p>        return ResponseEntity.noContent().build();</p>
<p>    }</p>
<p>}</code>

This controller handles the following endpoints:

HTTP Method Endpoint Description
GET /api/persons Returns all persons
POST /api/persons Creates a new person
GET /api/persons/{id} Returns a single person
PUT /api/persons/{id} Updates a person
DELETE /api/persons/{id} Deletes a person

To run this application:

  1. Create a Spring Boot project with dependencies: spring-boot-starter-web, spring-boot-starter-data-jpa, h2
  2. Add the following to application.properties:
<code class="language-properties">spring.datasource.url=jdbc:h2:mem:testdb</p>
<p>spring.datasource.driver-class-name=org.h2.Driver</p>
<p>spring.jpa.database-platform=org.h2.Driver</code>

Testing the API: Use Postman or curl to test endpoints. For example, to create a person:

<code class="language-bash">curl -X POST http://localhost:8080/api/persons \
<p>  -H "Content-Type: application/json" \</p>
<p>  -d '{"name": "John Doe", "age": 30}'</code>

This returns the created person with an id generated by the database.

Important Note on Error Handling: In production systems, we’d implement robust error handling (e.g., using @ControllerAdvice for consistent error responses). This example prioritizes simplicity for educational purposes.

Summary

We built a complete CRUD API using Spring Boot, demonstrating the full set of REST operations. This example provides a solid foundation for building enterprise-grade REST services in Java. ✅