Search code examples
javaspring-bootresthttp-headershttprequest

How can I get the user_id from the request header instead of passing it as a request parameter? And then send it back through the header


For various REST api endpoints, the user_id will reach the backend, needed for further processing and then, sent back as a response to the front end.

I have a feeling I can do this through the header instead of passing it as a path parameter each time, except I can't seem to find the relevant information yet.

At the moment I send the response as a ResponseEntity. I would like, if possible, to keep this option.

I am using Java and Spring Boot.


Solution

  • I have decided that the best approach for my scenario, where I only need to fetch the user id and then respond back with it, is to use the @RequestHeader("userId") Long userId annotation.

    Let's have a look at how I had configured the enpoint initially:

    @PostMapping(path = "/add-follower/{userIdForFollowing}/{currentUserId}")
    public ResponseEntity<String> addFollower(@PathVariable ("userIdForFollowing") Long userIdForFollowing, @PathVariable Long currentUserId)
    {
        Follow newFollow = followService.returnNewFollow(userIdForFollowing, currentUserId);
        
        newFollow = followService.saveFollowToDb(newFollow);
    
        return new ResponseEntity<>("Follow saved successfully", HttpStatus.OK);
    }
    

    Now, let's look at how I refactored the endpoint to fetch the id's from the header and return them in the response:

    @PostMapping(path = "/add-follower")
    public ResponseEntity<String> addFollower(@RequestHeader("userIdForFollowing") Long userIdForFollowing, @RequestHeader("currentUserId") Long currentUserId)
    {
    
        Follow newFollow = followService.returnNewFollow(userIdForFollowing, currentUserId);
        newFollow = followService.saveFollowToDb(newFollow);
    
        //here I will add more code which should replace the String in the ResponseEntity.
        return new ResponseEntity<>("Follow saved successfully", HttpStatus.OK);
    }