REST api to fetch MongoDB data - JAVA
image by https://www.codeproject.com/

REST api to fetch MongoDB data - JAVA

This is an article to show how we can create a rest api to fetch mongo database colletion using JAVA and JAVAX.

REST API

  • REST or RESTful API design (Representational State Transfer) is designed to take advantage of existing protocols. While REST can be used over nearly any protocol, it usually takes advantage of HTTP when used for Web APIs. This means that developers do not need to install libraries or additional software in order to take advantage of a REST API design.

MongoDB

  • MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import dev.morphia.Datastore;
import dev.morphia.Morphia;

specify path for rest api as

@Path("/collections")

Media type is very important parameter which which may block if it does not exists.

public class ListController {
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	
    public  Response getMsg( @HeaderParam(value = "Authorization") String auth, Test1 test  ){  

Create MongoDB connection as below:

  • create connection
  • db object filtering with query objects
  • find service for finding data inside mongo db
MongoClient client = new MongoClient("server host or ip", port); //connect to mongodb


		DB db = client.getDB("db_name");
		DBCollection table = db.getCollection("collection_name");
		
		BasicDBObject query = new BasicDBObject();
		
		if(FinalSkillText != null){
			query.put("field1",  java.util.regex.Pattern.compile(FinalSkillText));
		}


		if(FinalCountry != null){
			query.put("field2",  java.util.regex.Pattern.compile(FinalCountry));
		}


		if(FinalResumeTitle != null){
			query.put("field3",  java.util.regex.Pattern.compile(FinalResumeTitle));
		}
		
		int count = 0;
		count =  (int) table.find().count();
		if(SkillText != null || Country != null || ResumeTitle != null){
			count =  (int) table.find(query).count();
		}
		List<Integer> ct = new LinkedList<Integer>();
		ct.add(count);
		
		DBCursor cursur  =  (DBCursor) table.find(query).skip(FinalPageSize*(FinalPageNo-1)).limit(FinalPageSize);
	
		Iterator<DBObject> iterator = cursur.iterator();
		
        List<DBObject> list = new LinkedList<DBObject>();

Use LIST operator and loop for records and send in response. JAVAX is packaged with standard classes makes easy to send response as below.

return Response.status(200).entity(json).build();

Following sets CORS filter and Headers for response in REST api.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
 
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("CORSFilter HTTP Request: " + request.getMethod());
 
        // Authorize (allow) all domains to consume the content
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
 
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Credentials", "true");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Max-Age", "1209600");
        
        
        
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
 
        // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }
 
        // pass the request along the filter chain
        chain.doFilter(request, servletResponse);
    }

Full Snippet for Rest Main web api with static Authorization and Basic Validations.

package spring.mvc;


import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import dev.morphia.Datastore;
import dev.morphia.Morphia;


@Path("/resumes")


public class ListController {
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public  Response getMsg( @HeaderParam(value = "Authorization") String auth, Test1 test  ){  
		 String Authorization = "ASDFSFSDFSDDFGHF435FGFHFGHF";
		 System.out.println(auth);
		 String NewToken  = auth.substring(7);
		 System.out.println(NewToken);


		 //******Validate Token	
		 if (auth != null && !auth.startsWith("Bearer ")) {
			 String msg = "Token is Invalid";
			 return Response.status(400).entity(msg)
					 .build();
		 }
		 
		 if(!NewToken.equals(Authorization)){
			 String msg = "Token is Invalid";
			 return Response.status(400).entity(msg)
			     .build();
		 }
	
		 int PageNo = test.getPage();
		 int PageSize = test.getLimit();
		 String str1 = Integer.toString(PageNo); 
		 String str2 = Integer.toString(PageSize); 


		 String fieldname1 = test.getField1();
		 String fieldname2 = test.getField2();
		 String fieldname3 = test.getField3();


		 //******Handlimg Param Value		
		 int FinalPageNo = 0;
		 if(str1 != null){
		     FinalPageNo = PageNo;
		 }
	
		 int FinalPageSize = 0;	
		 if(str2 != null){
			 FinalPageSize = PageSize;
		 }
	
		 String fieldname1 = "";	
		 if(field1 != null){
			 fieldname1 = fieldname1;
		 }
	
		 String fieldname2 = "";
		 if(field2 != null){
			 fieldname2 = fieldname2;
		 }
	
		 String fieldname3 = "";	
		 if(field3 != null){
			 fieldname3 = fieldname3;
		 }

		
		MongoClient client = new MongoClient("server host or ip", port); //connect to mongodb


		DB db = client.getDB("db_name");
		DBCollection table = db.getCollection("collection_name");
		
		BasicDBObject query = new BasicDBObject();
		
		if(fieldname1 != null){
			query.put("field1",  java.util.regex.Pattern.compile(fieldname1));
		}


		if(fieldname2 != null){
			query.put("field2",  java.util.regex.Pattern.compile(fieldname2));
		}


		if(fieldname3 != null){
			query.put("field3",  java.util.regex.Pattern.compile(fieldname3));
		}
		
		int count = 0;
		count =  (int) table.find().count();
		if(field1 != null || field2 != null || field3 != null){
			count =  (int) table.find(query).count();
		}

		List<Integer> ct = new LinkedList<Integer>();
		ct.add(count);
		
		DBCursor cursur  =  (DBCursor) table.find(query).skip(FinalPageSize*(FinalPageNo-1)).limit(FinalPageSize);
	
		Iterator<DBObject> iterator = cursur.iterator();
		List<DBObject> list = new LinkedList<DBObject>();
		
		 
		while(iterator.hasNext()){
		       list.add(iterator.next());
		}
		 
		Map<String, LinkedList> objMap = new HashMap<String, LinkedList>();
		objMap.put("Result", (LinkedList) list);
		objMap.put("Count", (LinkedList)ct);
		 
		String json = new Gson().toJson(objMap);
		System.out.println(json);

		return Response.status(200).entity(json).build();
	}
}


To view or add a comment, sign in

More articles by Nagaraja Kharvi

Others also viewed

Explore content categories