By the early 19th century Lima was slowly losing its influence. Other regions of the Spanish Empire in South America grew in importance and began to rebel against the Spanish colonization. While Spain was invaded by Napoleon and was busy defeating its borders, most Spanish colonies in South America took the advantage of these circumstances and sought independence, but Lima stayed loyal. Peru's rebellion didn't emerge from within Peru.
In December 1820 a rebel army under the leadership of the Argentinean José de San Martín defeated the Spaniards in the battle of Pisco and invaded Lima. From the north Simón Bolívar came to help. Finally on the 28th of July 1821 José de San Martín officially declared Peru's independence at the Plaza Mayor or also known as Plaza de Armas in Lima. But the fighting between the patriots and royalist continued until the complete defeat of the Spanish troops in Ayacucho 1824. During this time Lima suffered greatly due to the disruption of trade and the forced contributions imposed by both sides.
After the war political turmoil and the lack of economic resources slowed down Lima's recovery. In the middle of the 19th century a boom based on guano exports allowed several improvements to the situation (guano = droppings of seabirds - an effective fertilizer and gunpowder ingredient).
In 1850 a railroad line between Lima and Callao was completed. Others along the beach up to Chorrillos followed and five years later Lima started using gas lighting. To make way for the expansion of Lima the city walls were torn down in 1872.