0

I'm building a REST API with Spring Boot and I have a controller for handling tasks. When I try to send a POST request to /tasks using Postman, I get a 404 Method Not Allowed error.

My goal is to send a JSON body to create a new task. I expect POST /tasks to be routed to the createTask() method in my controller, but it doesn't work. Other methods doesnt work also though im not sure


main class with @SpringBootApplication:

@SpringBootApplication
public class ToDoManagerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ToDoManagerApplication.class, args);
    }

My TaskController class

package az.edu.turing.todomanager.controller;
import az.edu.turing.todomanager.model.Task;
import az.edu.turing.todomanager.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController



public class TaskController {

    private final TaskService taskService;

    public TaskController(TaskService taskService) {
        this.taskService = taskService;
        System.out.println("taskcontroller init");
    }


    @GetMapping
    public List<Task> getAllTasks(){
        return taskService.getAllTasks();

    }

    @GetMapping("/{id}")
    public ResponseEntity<Task> getTaskById(@PathVariable Long id) {
        return taskService.getTaskById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public Task createTask(@RequestBody Task task){
        return taskService.createTask(task);

}
    @PutMapping("/{id}")
    public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
        try {
            Task task = taskService.updateTask(id, updatedTask);
            return ResponseEntity.ok(task);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
        taskService.deleteTask(id);
        return ResponseEntity.noContent().build();
    }

}



My TaskServiceImpl class:

package az.edu.turing.todomanager.service.impl;

import az.edu.turing.todomanager.model.Task;
import az.edu.turing.todomanager.repository.TaskRepository;
import az.edu.turing.todomanager.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class TaskServiceImpl implements TaskService{
    private final TaskRepository taskRepository;

    @Override
    public List<Task> getAllTasks() {
        return taskRepository.findAll();
    }

    @Override
    public Task createTask(Task task) {

        return taskRepository.save(task);
    }

    @Override
    public Optional<Task> getTaskById(long taskId) {
        return taskRepository.findById(taskId);
    }

    @Override
    public Task updateTask(Long taskId, Task updatedTask) {
        return taskRepository.findById(taskId)
                .map(existingTask -> {
                    existingTask.setName(updatedTask.getName());
                    existingTask.setDueDate(updatedTask.getDueDate());
                    existingTask.setStatus(updatedTask.getStatus());
                    return taskRepository.save(existingTask);
                })
                .orElseThrow(() -> new RuntimeException("Task not found with id: " + taskId));
    }

    @Override
    public void deleteTask(Long taskId) {
        taskRepository.deleteById(taskId);

    }


}




My application.properties:

spring.application.name=to-do-manager
spring.datasource.url=jdbc:postgresql://localhost:5432/todomanager
spring.datasource.username=postgres
spring.datasource.password=mypassword

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
management.endpoints.web.exposure.include=*

I have Verified URL and method in Postman

Added @RequestMapping("/tasks") at class level

Confirmed controller is initialized

Restarted app multiple times , but still either 405 or 404 error,

http://localhost:8080/tasks-----> POST---> 404 error http://localhost:8080/todomanager/tasks------> 404 error

3
  • 1
    where is the @RequestMapping("/tasks")? Commented Jul 11 at 21:25
  • you mentioned in your post: "Added @RequestMapping("/tasks") at class level" but your code doesn't reflect that here. Also at class level how is the framework supposed to know which method to call when you have many in the class? at class level you are forcing all endpoints to be prefixed with "/tasks" so for instance @GetMapping("/{id}") becomes /tasks/{id} you need to be specific with the mappings. Commented Jul 11 at 22:49
  • can you share your repository interface, and Task class? also, share your request body Commented Jul 13 at 12:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.