1

I was looking at a few post regrading query parameters in my URL and I couldn't quite find what I was looking for.

So far the external API I am fetching data from requires a specific I will call in this case "tag" parameter when making HTTP request in the browser.

Here is my Post model with a tag defined as a field

package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;


    private String tag;

    public Post() {

    }

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

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;

@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }



    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

2 Answers 2

2

The tag request parameter should be sent to the url. And your getPosts() method tag parameter should be correct as follows.

getPosts(@RequestParam String tag)

value field is used in @RequestAttribute

Sign up to request clarification or add additional context in comments.

Comments

1

Simply change your method to

@GetMapping("/api/posts")
public ResponseEntity<?> getPosts(@RequestParam("tag") String tag){...}

Then you also need to send that query param in url like

http://localhost:8080/api/posts?tag=java

1 Comment

Also can be like this . public ResponseEntity<?> getPosts(@RequestParam String tag){...}

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.