Home > front end >  How can I get the user_id from the request header instead of passing it as a request parameter? And
How can I get the user_id from the request header instead of passing it as a request parameter? And

Time:01-25

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.

CodePudding user response:

example based on

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

edited to add readign header from request

@RequestMapping("/handle")
public ResponseEntity<String> handle(HttpServletRequest httpRequest) {
  String userId= httpRequest.getHeader("user_id");
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.set("user_id", userId);
  return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

CodePudding user response:

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);
}
  • Related