The decision could open the door for other states in Mexico, the world's second-most populous Catholic country, to follow the capital's lead in relaxing laws that criminalise abortion, legal experts said.
The judges found that Mexico's constitution did not explicitly guarantee the right to life of a fetus, and that the interests of the unborn had to be balanced with those of women seeking an abortion.
The conservative federal government had challenged the law, backed by anti-abortion groups and the church.
After three days of debating the issue, a majority of judges rejected their claim that the law - introduced last April by the capital's left-wing government - was unconstitutional.
"The legal and social impact of this decision are undeniable," Guillermo Ortiz Mayagoitia, the president of the court, said.
Since the law was applied on April 27 last year, about 12,000 women aged between 18 and 29 have had abortions in 12 clinics in the capital, human rights groups say.
Between 1990 and 2005, an average of 13 women died per year due to clandestine abortions in Mexico City, according to pro-abortion groups.
The ultra-conservative Provida organisation said eight women had died per year.
Since last April only one woman, aged 16, is believed to have died during an abortion, due to her doctor being misinformed about the length of her pregnancy.
Throughout Mexico, states allow abortions only under limited circumstances, such as rape and incest.
However, human rights groups say that in practice such abortions are difficult to obtain.