HTTP API to Grafana Cloud Loki

I have an Grafana Loki HTTP API working right now.

const url = new URL('http://not-sharing-this:3100/loki/api/v1/query_range');
url.searchParams.set('query', '{job="bob_job", branch="master"}');
url.searchParams.set('limit', '500');

console.log(url.toString());
fetch(url.toString(), {
    method: 'POST',
})
    .then((response) => response.json())
    .then((obj) => {
        console.log(obj);
    })
    .catch(console.error);

I need to transition to use Grafana Cloud Loki. I’m not finding the resources I need, maybe I don’t know the keywords to google, and I’m really at a loss.

Hi @taylormo !

If you wish to push logs to Grafana Cloud using the Loki HTTP API, update the URL in your example to your hosted Loki instance URL and add authentication using basic_auth.

In your account portal, click on the “details” button next to Loki to find the Loki username (which is the instance ID) and generate an API Key or Access Policy token for auth.

The Loki HTTP API endpoint for your Grafana Cloud’s instance should look something like https://$region.grafana.net/loki/api/v1/push

For example, my endpoint in us-central1 is:

https://logs-prod-us-central1.grafana.net/loki/api/v1/push

Note that in general, we recommend using the official client options to send logs to Grafana Cloud since the Loki HTTP API is not considered stable.

1 Like

@Melody Can you extrapolate on what you mean by region?

const tmp = new URL('https://<this>.grafana.net/loki/api/v1/query_range');
tmp.searchParams.set('query', '{job="bobjob"}');
fetch(tmp.toString(), {
    method: 'POST',
    headers: {
        'Authorization': 'Basic ' + btoa(user + ":" + apikey)
    },
})
    .then((response) => console.log(response));

This yields the error:

Access to fetch at 'https://<this>.grafana.net/loki/api/v1/query_range?query=%7Bjob%3D%22bobjobs%22%7D' from origin 'http://<wherever>.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

you use the POST method,but the offcial say this API is a GET method

Hello,friends.Have you already solved this problem?I use the cURL tool and request the Loki API:curl -s -u “7xxx4:” https://logs-prod-020.grafana.net/loki/api/v1/labels,and I can get the right results:{“status”:“success”,“data”:[“container_name”,“filename”,“instance”,“job”,“namespace”,“stream”]}

If you use the headers,you should use Base64 to encode your userID+apiKey.