0

I'm new to creating web services in Java, thus the question.

I have an object,

public class Course {

    private int _id;
    private String _name;
    private Person _person;
}

I have data about the object stored in a file, which I've already parsed and stored in a local array list.

My DataService object does this.

public DataService(){

        _personList = new ArrayList<>();
        _courseList = new ArrayList<>();

        //logic to parse data and read into a QueryHandler object.

        _handler = new QueryHandler(_personList, _courseList);

    }

Now this data service has a GET method which displays the list of all courses.

   @GET
    @Produces("application/JSON")
    public ArrayList<Course> getAllCourses(){
        return _handler.getAllCourses();

    }

My question is how do I expose this method as an endpoint, so that the caller can get a link like example.com/getAllCourses or something like example.com/getCourseById/21(method already created) which will return the data in JSON format ?

1 Answer 1

1

You have to add @Path("/course") to your class and change your method to

@GET
@Path("/getAllCourses")
@Produces("application/JSON")
public ArrayList<Course> getAllCourses(){
    return _handler.getAllCourses();

}

And if you want to get a specific id you'll write

@GET
@Path("getCourseById/{id}")
@Produces("application/JSON")
@Consumes("application/JSON")
public Course getCourseById(@PathParam("id") int id){
    return _handler.getCourseById(id);

}

The path will be host.com/course/getAllCourses or host.com/course/getCourseByid/1 for example

Here is a doc' about it JAX-RS

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

4 Comments

Just one doubt, my application is using GlassFish as a server, how do I access these API's on a browser.
Are you using maven?
Nope I'm using the Gradle build system.
(Late answer) You have to type the URL ;)

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.