Hello I'm trying to create a POST method and I keep getting the "404 Request method 'GET' not supported" error. Below I'll post my Rest controller and below that I'll post my service class. The only thing not working is the #PostMapping method.
#RequestMapping("/ATM")
public class ATMController {
private ATMService atmService;
#Autowired
public ATMController(ATMService atmService) {
this.atmService = atmService;
}
#GetMapping(path = "/{id}")
public ATM getATMById(#PathVariable long id){
return atmService.getByID(id);
}
#PostMapping(path = "/{id}/withdraw/{amount}")
public List<Bill> withdrawMoney(#PathVariable long id,#PathVariable float amount){
return atmService.withdrawMoney(id,amount);
}
}
#Service
public class ATMService {
private ATMRepository atmRepository;
private BillRepository billRepository;
#Autowired
public ATMService(ATMRepository atmRepository, BillRepository billRepository) {
this.atmRepository = atmRepository;
this.billRepository = billRepository;
}
public void save(ATM atm) {
atmRepository.save(atm);
}
public ATM getByID(Long id) {
return atmRepository.findById(id).get();
}
public List<Bill> getBillList(Long id) {
return atmRepository.findById(id).get().getBillList();
}
#Transactional
public List<Bill> withdrawMoney(Long id, float amount) {
List<Bill> allBills = getBillList(id);
List<Bill> billsToWithdraw = new ArrayList<>();
float amountTransferred = 0;
for (Bill bill : allBills) {
if (bill.getValue() == 100) {
billsToWithdraw.add(bill);
amountTransferred += bill.getValue();
}
if (amountTransferred == amount) {
for (Bill billToWithdraw : billsToWithdraw) {
billRepository.delete(billToWithdraw);
}
return billsToWithdraw;
}
}
return null;
}
}
I don't see the issue, I've tried switching to #GetMapping and removed the actual transaction "billRepository.delete(billToWithdraw);" and the method then returns the correct bills.
As the error says 404 Request method 'GET' not supported means you are making a GET request instead of POST.
You can make use of tools like Postman to make a post request. Hitting /{id}/withdraw/{amount} via any browser will prompt a GET request and not a POST request.
The issue is that you are sending a GET request to an end point that is configured to accept only POST request. This will probably help you to test them.
How to test
In case you GET requests -
You CAN directly check the api from the browser address bar. Type in the api and hit enter.Its that Simple!
You can use a tool such as Postman, SoapUI, etc to send a GET request.
You could write an html form with action="get mapping uri" and method="GET"
If your API uses any documentation or design tools such as swagger you can test it from its interface.
In case you POST requests -
You CANNOT directly check the api from the browser address bar.
You can use a tool such as Postman, SoapUI to send a POST request.
You could write an html form with action="post mapping uri" and method="POST".
If your API uses any documentation or design tools such as swagger you can test it from its interface.
In my case the problem was that I called https://localhost:8080/my-service but the port 8080 not supports HTTPS so I changed my call to http://localhost:8080 and resolved my problem. However when calling a http with https spring makes internally a GET Request
Related
I am new to spring boot and I am trying to send a simple POST and DELETE request via postman, but i am stuck with error 500.Can someone point the errors in my code?.
I have spring boot simple app build with maven and run in embedded tomcat through STS.
i tried these requests for POST and DELETE:
POST:
http://localhost:8080/api/v1/addMenu
The Error status:
{"timestamp":"2022-08-05T13:41:37.984+00:00","status":500,"error":"Internal Server Error","path":"/api/v1/addMenu"}
DELETE:
http://localhost:8080/api/v1/delete/5
Error Status:
{"timestamp":"2022-08-05T13:45:51.548+00:00","status":500,"error":"Internal Server Error","path":"/api/v1/delete/5"}
Here is my controller code:
#RestController
#RequestMapping("/api/v1")
public class MenuController {
#Autowired
private MenuRepository menuRepository;
#GetMapping("/getMenu")
public List<Menu> list() {
return menuRepository.findAll();
}
#GetMapping
#RequestMapping("/getMenu/{id}")
public Menu get(#PathVariable Integer id) {
return menuRepository.getReferenceById(id);
}
#PostMapping("/addMenu")
public Menu create(#RequestBody final Menu menu) {
return menuRepository.saveAndFlush(menu);
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable Integer id) {
menuRepository.deleteById(id);
}
#RequestMapping(value = "{id}", method = RequestMethod.PUT)
public Menu update(#PathVariable Integer id, #RequestBody Menu menu) {
Menu existingMenu = menuRepository.getReferenceById(id);
BeanUtils.copyProperties(menu, existingMenu, "buy_id");
return menuRepository.saveAndFlush(existingMenu);
}
}
MenuRepository:
public interface MenuRepository extends JpaRepository<Menu, Integer> {}
The port is default in 8080.
I tried the Get request and PUT request, which worked perfect with no errors, but the POST and DELETE gives error status. Can someone point the mistake in the code.?
Thanks
There is no mistake in the code you've posted. The 500 error means there is a problem internally with your server. This could be any sort of Exception. There doesn't appear to be anything wrong with your controller itself. Since you are getting a 500 error and not a 404 error, that means that the mappings exist and postman is able to contact them. The server is getting an error, but postman doesn't care about it. Postman only sees that something happened on the server side that caused a problem.
I believe a bit of debugging is in order. Set a breakpoint in your controller and attempt to run the code in the code evaluation to see what the error is. That should get you on track to find how to fix it.
I am trying to access the POST API from my spring app to angular but little bit confused how to use and access the given API in my angular app.
Spring REST API
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
The given API is fetching the welcome message details from my oracle DB and returning a string value. I am trying to access the given REST API in my angular code through services. I had define the post service as follows
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
const headers = {'content-type':'application/text'}
return this.http.put("http://localhost:8080/API/getWelcomeMessage",null,
{'headers':headers});
}
}
As the post method requires three arguments URL, Body and header. But in my case my spring REST API doesn't contain any body and returning a string. So, I had define the body as null and change the header type to text as it is JASON by default.
At last, I am trying to access the given service method by injecting it in my component as follows-
export class LoginComponent implements OnInit {
message:string;
constructor(private loginService : LoginService) { }
ngOnInit(): void {
this.loginService.welcomeMessageService().subscribe(
response =>{
console.log(response);
this.message = response;
}
)
}
}
But when I am trying to assign the response to the string I am getting the error that string cannot be assigned to the object. I am little bit confused why this error is occurring as I had also changed the header type to string while defining my service but still getting the error.
It can be a great help if anybody guide me regarding this as I am new to angular and little bit confused with integration part of API with angular.
Use { responseType: 'text' } and also send an empty body not null
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
return this.http.put("http://localhost:8080/API/getWelcomeMessage",{},
{ responseType: 'text' });
}
}
Maybe you have copied the function wrong but check also here
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
This is a Post method not a put that you are trying to call
As for cors error add the following to the backend just above #Controller or #RestControler whatever you have
#CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
I have a front-end react application, where i make a request to a REST Jax-RS backend server.
Here is the request being sent
deletePost = (post) =>{
return deleter(config.restUrl + `posts/${post}`)
}
Here i get the standart URL for my backend, with a 'deleter' function, which is just a standardized fetch delete method (which has also worked with other entities as well).
Here is my Jax-RS resource:
#DELETE
#Consumes(APPLICATION_JSON)
#Produces(APPLICATION_JSON)
#Path("/{id: [0-9]+}")
public Response deletePost(#HeaderParam("authorization") String token, #PathParam("id") Integer id) throws ResourceNotFoundException, AuthenticationException
{
AuthenticationContext authenticationContext = authenticationFacade.authenticateBearerHeader(token);
Post post = postFacade.delete(authenticationContext, id);
return Response.ok(gson.toJson(PostDTO.basic(post))).build();
}
The problem is that it gives me an error saying that the form is HTML/text:
MessageBodyWriter not found for media type\u003dtext/html, type\u003dclass com.group3.sem3exam.rest.dto.PostDTO, genericType\u003dclass com.group3.sem3exam.rest.dto.PostDTO
Since it's implying that it is the PostDTO that has the error, I went to check the basic method, which converts the entity into a Data Transfer Object, to be posted back to the client side.
public static PostDTO basic(Post post)
{
return new PostDTO(
post.getId(),
post.getContents(),
post.getCreatedAt(),
null,
ImageDTO.list(post.getImages(), ImageDTO::withoutUser)
);
}
Here it just calls the method which returns a new instance of the object.
I have not seen this error before, and I'm not sure how to handle it?
Try
return Response.status(Status.OK).entity(new Gson().toJson(PostDTO.basic(post))).build();
Hi friends I am using Angularjs and rest-servies but when I am calling rest services from service.js file something is goning wrong and it is throwing 400(bad request )
main.js
garantiesService.getTarifs($scope.recap.ageDirigeant,$scope.selectedCompany.zipcode)
.success(function(){
console.log('in success');
})
service.js
healthApp.factory('garantiesService', ['$http', function($http) {
var service = {
getTarifs: function(age,zipcode)
{
console.log("age : "+age);
console.log("zipcode : "+zipcode);
var directorHealthInsuranceInfo = {};
directorHealthInsuranceInfo.age=age;
directorHealthInsuranceInfo.department=zipcode;
return $http.post('rest-service/quotes/health /director',directorHealthInsuranceInfo);
}
};
return service;
HealthInsuranceController.java
#Controller
public class HealthInsuranceQuoteResource {
#RequestMapping("quotes/health/director")
#ResponseBody
public String quoteDirector(#RequestBody DirectorHealthInsuranceInfo info) {
System.out.println("------HealthInsuranceQuoteResult------");
return "hi";
}
DirectorHealthInsuranceInfo.java
#Value
public class DirectorHealthInsuranceInfo {
private String department;
private int age;
}
when I am sending the request it is throwing Bad Request 400 error.
I see that there is a space in the url you supplied to the http.post method.
"rest-service/quotes/health /director"
I don't know if that is causing it.
But I also see that you POST your request to the service. Are you sure that your endpoint has been set up for POST requests?
I would recommend creating a basic endpoint that you call with a GET request, and no parameters. Just to root out the problem.
I'm trying to find some manual how to test POST methods using jersey framework, only got examples for GET method.
Here's example:
#POST
#Path("add")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public Response addUser(JAXBElement<User> user) {
int code = userService.addUser(user.getValue());
if (code == 500) {
return Response.status(500).build();
}
return Response.status(code).entity(user).build();
}
Could you please post some POST method test example?
Thank you in advance.
After research I did it!
Here's my solution, it works just fine.
And it's rather integration test, but we can write unit tests in similar manner.
public class RestTest extends JerseyTest{
#Override
protected Application configure() {
return new Your_Resource_Config(); //Your resource config with registered classes
}
//#Before and/or #After for db preparing etc. - if you want integration tests
#Test
public void addUserTest() {
User user = new User();
user.setEmail("user2#mail.com");
user.setName("Jane Doe");
user.getUserRoles().getRoles().add("supertester");
Entity<User> userEntity = Entity.entity(user, MediaType.APPLICATION_XML_TYPE);
target("users/add").request().post(userEntity); //Here we send POST request
Response response = target("users/find").queryParam("email", "user2#mail.com").request().get(); //Here we send GET request for retrieving results
Assert.assertEquals("user2#mail.com", response.readEntity(User.class).getEmail());
}