#3 Passing Query Paramater In REST API

Please go through series 1 and series 2 before starting this tutorial.

In my last tutorials I have explained that how can we create simple hello world API and how can we access DB by using JDBCTemplate. JDBCTemplate is spring framework's library which make easy to access the DB.

So now let me continue to the topic. Lets extends EmployeeDao to another method which will fetch Employee data based on email id passed. Please see the example below:





Please note that I have added another method with email parameter. Now lets implement this method in interface implementation class ( named as EmployeeDaoImpl):




Now lets write REST api to access employee data with email passed. Write following method in your Controller class:











We write another REST api names getemployee with request parameter email.  I have used @RequestParam for parameter. You can make parameter as required OR optional.


Now to access api you can call rest url as given below, by passing query parameter in URL. You can also try this api with POST method as you can see that I have given GET and POST in RequestMethod.




So finally we have successfully made our REST api in which we can pass query parameter and can fetch result.


Calling Rest Api With JSON Body:


So in above example we have seen that we can pass 1,2 OR any number of parameters in our query param and can get response from our REST api. But what if we have to pass some huge number of data like 100 OR 200 values, I don't think it would be a good idea to use query parameter in this case. 

We can pass big data in form of JSON body OR even we can pass hierarchical data as well by using JSON body. So to use JSON body we have to make POST call.

So lets start implementation, First create EmployeeFilter class and define all properties which you are expecting in JSON body. Please note that property name should be same as JSON key name.



For our example we used email only.

Now lets write REST api method:


We have used @RequestBody for JSON request. We have used parameter as object of EmployeeFilter. By using this it will automatically assign JSON value to EmployeeFilter object, based on key name and property name. So now we can simple fetch email and can pass Dao method.

Another way of doing this is that we can manually fetch JSON from request object and can get any key by using JAVA spring methods. But the method explained above is very easy and flexible to use.


So now we are good to write our simple basic rest api's. I will be posting further advance level things in my blogs, so be connected :)






Comments

Popular posts from this blog

#2 Simple Spring Rest Api with JDBC connection

#1 My First Rest API With Spring Boot Freamwork

Swift Initialization