The first church was built by the Emperor Constantius II (337-361), son of Emperor Constantine I (324-337), in 360. This church was constructed as a basilica with a wooden roof. In 404, during the riots against Emperor Arcadius, it was partially burned and destroyed.
The second church was ordered by Emperor Theodosius II (408-450) and built by architect Ruffinos in 415. This church is also constructed as a basilica with a wooden roof, 5 naves, 3 gates and a monumental entrance. The second Hagia Sophia was burned down in 532, during the riots called Nika Revolt against Emperor Justinian I (527-565).
The current Hagia Sophia was built by the two then prominent architects, Isidore of Miletus (Milet) and Anthemius of Tralles (Aydın), by the order of Emperor Justinian I. The construction that lasted 5 years long began on February 23, 532, 1000 masters and 10,000 workers were employed and the church was inaugurated on December 27, 537.
The ceiling mosaics decorated with floral and geometric motifs are the original ones made in the 6th century, but other mosaics with depictions were made after the ending of the iconoclast movement.
After the conquest of İstanbul in 1453 by Sultan Mehmed II the Conqueror (Fatih), Hagia Sophia was converted into a mosque. According to some historical documents, the church was in ruins. However, after the conquest, not only it has not been destroyed, but it has also been preserved in the best manner since the present day, thanks to strengthening and renovation works. Furthermore, with the addition of structures in Ottoman style, the building continued to be a sacred space and a place for worship.
In the 16th and 17th centuries, the minbar, the mihrab, daises for sermon and wood balusters were added to the interior. During the reign of Sultan Mahmud I, a library was built. The tiles here are among the distinguished examples dating from the 16th century.
Minarets were erected in different periods, Sultan Mahmud I built a fountain for religious ablutions (şadırvan) and a primary school in the courtyard of Hagia Sophia, and a timekeeper's building (muvakkithane) was constructed during the reign of Sultan Abdülmecid. There are the mausoleums (türbe) of Murad III, Mehmed III, Sultan Selim II and princes in the southern courtyard of Hagia Sophia. The building that served as a baptistery in the Byzantine era was converted into the mausoleum of Sultan Mustafa I and Sultan İbrahim. It is known that Sultan Mehmed II built a religious school (medrese) to the north of it, after converting Hagia Sophia into a mosque.
Hagia Sophia was converted into a museum in November 24, 1934, by a Cabinet decision upon the proposal of Mustafa Kemal Atatürk, and opened to visitors on February 1, 1935.