The evidence so far indicates that ranitidine (RAN) contains N-nitrosodimethylamine (NDMA), a strong carcinogen, which is extremely harmful to human health under long-term exposure. Hence, a well-design Z-scheme heterostructure composed of 3D MgIn2S4 micro-flower and 2D g-C3N4 nanosheets was fabricated and used to remove RAN. The optimal photocatalyst (MG-30) exhibited the fastest RAN degradation rate of 0.24685 min−1 within 30 min under visible light, which was 78.1 and 19.8 times higher than those of bare MgIn2S4 and g-C3N4, respectively. Impressively, MG-30 was exceedingly resistant to environmental variations including organic matter, inorganic salts and aqueous substrates. In the meantime, MG-30 boasted the merit such as wide pH range for RAN removal. The excellent results originated from the construction of Z-scheme heterojunctions, which improved the carrier separation efficiency and retained the strong redox ability of MG-30, thereby contributing to the creation of rich active species. Meanwhile, the 3D/2D structure of MgIn2S4/g-C3N4 overrode the limited reflection of visible light. The active species analyses revealed that superoxide radical (·O2−) and hydroxyl radical (·OH) mainly participated in RAN degradation. Furthermore, the possible degradation pathways of RAN and toxicity analysis of intermediates produced were presented. This work emphasizes practical application potential of Z-scheme heterostructure photocatalysts for emerging contaminants degradation in wastewater.