Getting data from Services

Enonic version: 7.13
OS: Windows 11 (Using Enonic Cloude)

Hi. i am wondering if there is any easy way to get data from a service

I have made a service undere resources/services/ and created a service url. But i can’t find out how to get that data into a part, as an example i want pages/default/default.js to be able to acces / call the service and acces the data. this is because i want to have several pages acces the same data from the service.

Is this possible?

A shared lib should do the trick. If its server side sharing of data.
Just have a function calling some query to get the data, and reuse that function in the places where you need the data.

This is ofc server side.

If its client side you need to pass the service url to frontend. Some way the client javascript code can access it. I often use data-attributes for this. Then you can use fetch or ajax or you prefer method to do a http request to the server.

Can you tell me more of the usecase or how you need to access the data?

1 Like

Hi, thanks for the reply, i got it to work somhow, by just having a request(path/to/file) in the controller where i need the data. i dont know if this is bad practise or if this is normal, and if so. should it be under libs?

I’d like to reiterate this question:

Can you tell me more of the usecase or how you need to access the data?

Based on your initial post, I’m getting some bad vibes… I hope you’re not trying to call an XP service from within your page controller in order to fetch data from XP! That would double the amount of HTTP requests which is not just inefficient and slow, it can also cause serious performance problems at scale. If your usecase is to “fetch common data in XP” and re-use code across your application, you should do that by importing functions from other parts of your application, not go outside of the application logic and do the roundtrip via an HTTP request into a service.

A typical reason to use HTTP services is either if your application needs to respond to end-user client requests (e.g. HTML forms) or if your application is serving as an API for other external systems.

The usecase is that i need to different pages, but i need them to have the same header and footer, so how i have done it now is that i have just made a file in lib/appName/index.js (and export the functions) and in the controllers where i need acces to the given function on the server side i just use appLib = pbs: require(‘/lib/appName’).

I saw that serveces whas a bad choice. so i made it into a lib. i think this should be correct and good practise, but i migth be wrong

1 Like

I see that the main issue for me here is a somwhat only basic use of JS, im more used to Pyhton and Java. thanks for the help

I think you’re on the right track now! <3

Also check out serviceUrl() in the portal lib. It will create the URL to your service so you can drop any hardcoding.