Toni
Toni

Reputation: 1

Getting 404 Error when calling a Spring Boot API

I wrote a few request mappings and connected my Spring Boot application to a Postgresql DB using JPA. However, when I try to call the API, I get the following message: {"timestamp":"2021-01-30T21:58:34.028+00:00","status":404,"error":"Not Found","message":"","path":"/api/v1/sessions"}. I tried printing a message when the API is called and it works so I think it might have something to do with the JPA connection? (I also tested if the DB and credentials are good using SQL Shell, and they are ok)

My model:

@Entity(name = "sessions")
public class Session {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long session_id;

    private String session_name;
    private String session_description;
    private Integer session_length;

    @ManyToMany
    @JoinTable(
            name = "session_speakers",
            joinColumns = @JoinColumn(name = "session_id"),
            inverseJoinColumns = @JoinColumn(name = "speaker_id"))
    private List<Speaker> speakers;

My controller:

@Controller
@RequestMapping("/api/v1/sessions")
public class SessionsController {

    @Autowired
    private SessionRepository sessionRepository;

    @GetMapping
    public List<Session> list() {
        System.out.println("Get method called");
        return sessionRepository.findAll();
    }

    @GetMapping
    @RequestMapping("{id}")
    public Session get(@PathVariable Long id) {
        return sessionRepository.getOne(id);
    }

My repository:

public interface SessionRepository extends JpaRepository<Session, Long> {
}

And lastly, my application properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/databaseName
spring.datasource.username=postgres
spring.datasource.password=mypasswordhere
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.show-sql=true

Upvotes: 0

Views: 556

Answers (2)

Ahmed Elghannam
Ahmed Elghannam

Reputation: 1

I faced this issue before and I found that I was missing "@ResponseBody"

@GetMapping(path= "/{Id}")
    public @ResponseBody Optional<User> findUserById(@PathVariable int Id) {
        // This returns a JSON or XML with the users
        return userRepository.findById(Id);

Upvotes: 0

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18939

    @GetMapping(value = "/{id}")<---remove Request mapping and also add the slash here
    public Session get(@PathVariable Long id) {
        return sessionRepository.getOne(id);
    }

Upvotes: 1

Related Questions