Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Delete Method in a RESTful web service

Tags:

java

rest

mysql

I am making my first RESTful web service (using MySQL). But I don't know how to remove records from a table by id.

This is what I have done so far:

  1. Search for a person by id and return the result(id, full name and age) in XML format:

    private PersonDao personDao = new PersonDao();
    //method which return a single person in xml
    @GET
    @Path("/getPersonByIdXML/{id}")
    @Produces(MediaType.APPLICATION_XML)
    public Person getPersonByIdXML(@PathParam("id")int id){
        return personDao.getPersonById(id);
    }
    
    // return JSON response
    
  2. Search for a person by id and return the result(id, full name and age) in JSON format:

    @GET
    @Path("/getPersonByIdJSON/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Person getPersonById(@PathParam("id")int id){
        return personDao.getPersonById(id);
    }
    
  3. Output all persons and return the result(id, full name and age) in JSON format:

    // the method returns list of all persons
    @GET
    @Path("/getAllPersonsInXML")
    @Produces(MediaType.APPLICATION_XML)
    public List<Person> getAllPersonsInXML(){
        return personDao.getAllPersons();
    }
    
  4. Insert a person in the database:

    //insert
    @GET
    @Path("/insertPerson/{fullName}/{age}")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveNewPerson(@PathParam("fullName") String fullName, @PathParam("age") int age) {
        Person person = new Person();
    
        person.setFullName(fullName);
        person.setAge(age);
    
        if (!personDao.savePerson(person)) {
            return "{\"status\":\"ok\"}  id="+person.getId();
        }
        else {
            return "{\"status\":\"not ok\"}";
        }
    }
    
  5. Edit a person in the database:

    //update
    @GET
    @Path("/insertPerson/{id}/{fullName}/{age}")
    @Produces(MediaType.APPLICATION_JSON)
    public String updatePerson(@PathParam("id") int id, @PathParam("fullName") String fullName, @PathParam("age") int age) {
        Person person = new Person();
        person.setId(id);
        person.setFullName(fullName);
        person.setAge(age);
    
        if (!personDao.savePerson(person)) {
            return "{\"status\":\"ok\"}";
        }
        else {
            return "{\"status\":\"not ok\"}";
        }    
    }
    
like image 294
Lev Avatar asked Oct 30 '25 20:10

Lev


1 Answers

If you want a DELETE resource:

@DELETE
@Path("/{id}")
public void deleteById(@PathParam("id")int id){
   personDao.deleteById(id);
}

As long as you have the deleteById method constructed then Thanks it!

Suggestions:

  • Your insert is a GET. Should really be a POST since you are creating something.
  • Your update is a GET. Should really be a PUT. Have fun and keep at it!!
like image 117
Jason McD Avatar answered Nov 02 '25 12:11

Jason McD