On 27 October 1807, Charles IV and Napoleon I signed the Treaty of Fontainebleau, which allowed the passage of French troops through Spanish territory to join the Spanish troops and invade Portugal, which had refused to obey the order of international blockade against England. As this was happening, there was the Mutiny of Aranjuez (17 March 1808), by which the crown prince, Ferdinand VII, replaced his father as king. However, when Ferdinand VII returned to Madrid, the city was already occupied by Joachim-Napoléon Murat, so that both the king and his father were virtually prisoners of the French army. Napoleon, taking advantage of the weakness of the Spanish Bourbons, forced both, first the father then the son, to join him in Bayonne, where Ferdinand arrived on 20 April.
In the absence of the two kings, the situation became more and more tense in the capital. On 2 May, a crowd began to gather at the Royal Palace. The crowd saw the French soldiers pulled out of the palace to the royal family members who were still in the palace. Immediately, the crowd launched an assault on the floats. The fight lasted hours and spread throughout Madrid. Subsequent repression was brutal. In the Paseo del Prado and in the fields of La Moncloa hundreds of patriots were shot due to Murat’s order against “Spanish all carrying arms”. Paintings such as The Third of May 1808 by Goya reflect the repression that ended the popular uprising on 2 May.
The Peninsular War against Napoleon, despite the last absolutist claims during the reign of Ferdinand VII, gave birth to a new country with a liberal and bourgeois character, open to influences coming from the rest of Europe. Madrid, the capital of Spain, experienced like no other city the changes caused by this opening and filled with theatres, cafés and newspapers. Madrid was frequently altered by revolutionary outbreaks and pronouncements, such as Vicálvaro 1854, led by General Leopoldo O’Donnell and initiating the progressive biennium. However, in the early 20th century Madrid looked more like a small town than a modern city. During the first third of the 20th century the population nearly doubled, reaching more than 850,000 inhabitants. New suburbs such as Las Ventas, Tetuán and El Carmen became the homes of the influx of workers, while Ensanche became a middle-class neighbourhood of Madrid.
The Spanish Constitution of 1931 was the first legislated on the state capital, setting it explicitly in Madrid.