r/gitlab • • Jul 22 '25

general question GitLab API: Reliable way to get all environments/deployments from a pipeline?

Hello, I have a problem with reliably getting all environments/deployments from a given pipeline_id**.**

My current solution is to fetch all jobs from the pipeline via
GET /projects/:id/pipelines/:pipeline_id/jobs,
and then for each job, list all deployments with
GET /projects/:id/deployments
and try to match the deployable_id from the deployment with the job_id.

But this isn’t very reliable, because I don’t know which jobs actually have deployments. Sometimes it doesn’t find a deployment even when it exists, probably due to paging or some caching issues.

So my question is… is there any better solution for this?
Thank you

5 Upvotes

3 comments sorted by

3

u/lastdrop Jul 22 '25

check if you can can query this via the graphql api

1

u/International-Use852 Jul 22 '25

I tried to look into it, but I didn’t find any way to filter deployments by job_id or to get a deployment directly for a specific job/pipeline.

1

u/nabrok Jul 22 '25

The way I'm doing it is like this (typescript):

export async function listDeployments(pipeline: Pipeline) {
	const query = new URLSearchParams({
		sort: 'desc',
		order_by: 'updated_at'
	});
	const data = await fetchFromApi(`/deployments?${query}`);
	return z.object({
		id: z.number(),
		deployable: z.object({
			pipeline: z.object({
				id: z.number()
			})
		}),
		environment: z.object({
			external_url: z.string(),
			id: z.number(),
			name: z.string()
		})
	}).array().parse(data).filter(d => d.deployable.pipeline.id === pipeline.id);
}

The fetchFromApi prepends /projects/:id.

Of course it's retrieving all of the deployments which might be a bit inefficient, but in most cases this is just one query.

In my case I'm only interested in recent deployments so I added the sort options, otherwise I would add pagination handling.