You can see the list of federated instances of each instance at https://example.com/instances
You can also get that data in json format by using https://example.com/api/v3/federated_instances
https://lemmy.readme.io/reference/getfederatedinstances
Mastodon and Lemmy are both using the ActivityPub protocol (Lemmy uses some extensions to federate downvotes and some other actions) to communicate between instances, but the API to interrogate a Mastodon, Lemmy, PixelFed or kbin instance will be different.