Tuesday, November 20, 2018

2. Adding an Endpoint

One of the primary reasons why one would be using spring framework would be to define rest based web services.  In this post, we will see how do we add an endpoint to our server. First, download and install your favorite IDE. I prefer IntelliJ IDEA but you can pick the IDE that you are comfortable with.
Let's open the project that we created in the previous blog post in the IDE. The source root for the project is <Project Name>/src/main/java. Once you open that directory, you will see the package of the project that you created. Within that, you will see the main for the spring application. The only thing that we change for now is to add scanBasePackages parameter in @SpringBootApplication annotation.

For now, we can leave the main as it is. The next step that we want to do is to add an endpoint. Create a new java class in your project. I call it HelloWorldEndpoint. To define an endpoint, we need to do the following things. The endpoint needs to have a path relative to the server root. We also need to know what operations are needed to be defined.
We will discuss the whole details of spring security later. So for now please remove security dependencies from your pom.xml. Following lines should be removed from pom.xml

It helps to look at a REST endpoint as an object with operations used to define their lifestyle state changes.

  • Path defines a class
  • Method GET is for reading the state of that object
  • Method POST is for creating a new object of that class
  • Method DELETE is for deleting an instance of that class
  • Method PUT is for updating the object
  • Method PATCH is for selectively updating the values.
Looking at our example, we are going to create a HelloWorld endpoint which will be used to manage the state of class Hello. Here is what class Hello looks like.

Now we look at our endpoint class. The class contains a single method GET which returns a temporarily created instance of Hello class.

Now we build the project.
$mvn clean package -DskipTests

And we can run the project.
$mvn spring-boot:run

Since maven build creates a single jar for each project. We can also run the project with the java command.
$java -jar target/tutorials-0.0.1-SNAPSHOT.jar

Most IDEs would allow you to build and run the project from within the IDE. You can do that as well. Now that the server is running we can test the endpoint that we had written. You can use tools like Postman but since it is a simple endpoint, we can just test it with curl command.
curl -X GET http://localhost:8080/hello

As we can see the JSON that is returned corresponds to the temporary object that we created and returned. Of course, this is too simplistic and we will look at doing something more substantial in the next blog post. 

No comments:

Post a Comment