Bells rang out from the capital's main cathedral and other churches in the city to signal a rejection of the verdict -- which opens the possibility of similar measures elsewhere in Mexico -- and a handful of youths protested outside the courtroom.
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.
"In all nations that have discussed abortion in constitutional courts there is a before and an afterwards," said Guillermo Ortiz Mayagoitia, president of the court.
"In Mexico, the afterwards is (now) beginning, the legal and social impact of this decision are undeniable."
Eight votes out of the 11 Supreme Court judges would have been necessary to abolish the law.
Since it was applied on April 27, 2007, some 12,000 women aged between 18 and 29 have had abortions in 12 clinics in the capital, 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 organization said eight women had died per year.
Since last April only one woman, aged 16, has died during an abortion, due to her doctor being misinformed about the length of her pregnancy.
In the rest of Mexico, states allow abortions only under limited circumstances, such as rape and incest, but rights groups say that in practice such abortions are difficult to obtain.