Expand my Community achievements bar.

SOLVED

How to create a RESTful API using servlet in CQ?

Avatar

Level 2

Hi,

 
I have a sling servlet as below:
 
@SlingServlet(
        label = "REST API", 
        metatype = true,
        resourceTypes = {"sling/servlet/default"},
        methods =  {"GET"},
        extensions = {"json"},
)
 
Can I call the servlet using below URL instead of /content/path.json?id=<category_id>
 
/content/path/<category_id>
 
this API should get <category_id> to run backend logic and return data.
 
Any suggestion?
 
Thanks
Jasmine
1 Accepted Solution

Avatar

Correct answer by
Level 2
Your servlet needs one of the two parameters - resourceTypes or path both will not work for the above scenario as neither your path is fixed nor your resourceType is defined.

A way to achieve it is to use selectors to provide category_id in the path and not use extensions. In your servlet you can extract the selector and have your logic of building the response/data accordingly.

Hope that helps.

Thanks

Ameesh

View solution in original post

4 Replies

Avatar

Level 7

Hi,
have you looked at this example. It's about getting relational data but you could modify it to something else :)
http://www.lucamasini.net/Home/sling-and-cq5/accessing-relational-data-as-sling-restful-urls
/Johan

Avatar

Level 10

Just to expand on this use case  -- here is a community article that talks about building an AEM service that consumes a 3rd party restful web service, calling the OSGi operation, getting back JSON, and displaying the results in a page component:

 http://helpx.adobe.com/experience-manager/using/restful-services.html

Avatar

Correct answer by
Level 2
Your servlet needs one of the two parameters - resourceTypes or path both will not work for the above scenario as neither your path is fixed nor your resourceType is defined.

A way to achieve it is to use selectors to provide category_id in the path and not use extensions. In your servlet you can extract the selector and have your logic of building the response/data accordingly.

Hope that helps.

Thanks

Ameesh

Avatar

Level 2

we use smth like this

@Component(immediate = true) @Service @Properties({ @Property(name = "service.description", value = "My Test Service"), @Property(name = "sling.servlet.paths", value = "/bin/myapp/test.json")}) public class TestService extends SlingAllMethodsServlet { public final static String PARAMETER_KEY = "id"; @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String id = request.getParameter(PARAMETER_KEY); // your logic below } }

You can call it by

http://mysite.com/bin/myapp/test.json?id=123