Home > OS >  How to Build a Spring Boot REST API with Java?
How to Build a Spring Boot REST API with Java?

Time:10-17

When I try to send any request with the API of this project by path(for example, http://localhost:8082/api/user), the result is always 404Not Found in postman.

why ???

file.propertise

spring.datasource.url = jdbc:mysql://localhost:3306/user
spring.datasource.username = user
spring.datasource.password = user
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port = 8082

User Model

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
}

Repository Classes

@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

Controller

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> findUserById(@PathVariable(value = "id") long id) {
        Optional<User> user = userRepository.findById(id);

        if(user.isPresent()) {
            return ResponseEntity.ok().body(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public User saveUser(@Validated @RequestBody User user) {
        return userRepository.save(user);
    }
}

CodePudding user response:

as far as i understand , you since you are passing a path variable you should try the url with a adding an id that exists in your database , else there is a property that specifies the initial base url for your application when it runs in a server server.servlet.context-path=/api for Spring 2.X versions and spring.data.rest.basePath=/api With Spring Boot 1.2 (<2.0). so to avoid redundant "api" in your path your request mapping should be @RequestMapping("/user"). Please let me know if this helped

CodePudding user response:

I won't see any issue in your code, looks fine to me. When I am running the same code on my laptop it is working fine. So looks like there is some other issue. I have a couple of questions.

  1. Is your application started properly?
  2. Which Spring Boot Version you are using?
  3. If possible can you please share the code repo link so that I can debug the issue?
  • Related