Skip to content
Advertisement

Postman returns null value after a successful post request

When I do a post request on Postman I receive a “200 OK” status. But doing a get request returns null JSON values

This is my user class

    public class User {
    private Integer id;
    private String name;
    private Date birthDate;
    
    public User(Integer id, String name, Date birthDate) {
        super();
        this.id = id;
        this.name = name;
        this.birthDate = birthDate;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return String.format("User [id=%s, name=%s, birthDate=%s]", id, name, birthDate);
    }

}

The UserDaoService class

    @Component
public class UserDaoService {

    static List<User> users = new ArrayList<>();
    
    public static int userCount = 3;
    
    static {
        users.add(new User(1,"Eva",new Date()));
        users.add(new User(2,"Mike",new Date()));
        users.add(new User(3,"Dave",new Date()));
    }
    
    public List<User> findAllUsers() {
        return users;
    }
    
    public User save(User user) {
        
        if(user.getId() == null)
            user.setId(++userCount);
        
        users.add(user);
        return user;
    }
    
    public User findOne(int id) {
        
        for(User user:users )
            if(user.getId() == id)
                return user;
        
        return null;
    }
    
}

and the controller

    @RestController
public class UserResource {
    
    @Autowired
    private UserDaoService service;

    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return service.findAllUsers();
    }
    
    @GetMapping("users/{id}")
    public User retrieveUser(@PathVariable int id) {
        return service.findOne(id);
    }
    
    @PostMapping("/users")
    public void createUser(User user) {
        User saved = service.save(user);
    }
    
}

This is the post request I make

    {
    "name": "Luna",
    "birthDate": "2000-08-23T23:58:45.849+00:00"
}

I didn’t pass in an ID because that is covered in the backend. On making a get request the name and birthDates both have null values but the ID is set correctly.

Any ideas where I could have gone wrong?

Advertisement

Answer

you are missing @RequestBody in the post method param

  @PostMapping("/users")
    public void createUser(@RequestBody User user) {
        User saved = service.save(user);
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement