The war grew out of the Mexican conflict with Texas. After having won its independence from Mexico in 1836, the Republic of Texas was annexed by the United States in 1845; however, the Mexican government still considered Texas a part of their country. That same year the United States government offended Mexico by offering to purchase California and New Mexico from them.
President James K. Polk ordered General Zachary Taylor to seize disputed Texan land settled by Mexicans. Fighting began in April 24, 1846 when Mexican cavalry entered an area claimed by both the US and Mexico, between the rivers Rio Grande and Nueces, and surrounded a US scouting party under General Zachary Taylor; several were killed. After the border clash and battles at Palo Alto and Resaca de la Palma, the US Congress declared war on May 13, 1846. Northern Whigs generally opposed the declaration of war while Southerners supported it. Mexico declared war on May 23.
After the United States declared war on Mexico, US forces took several cities in California including Los Angeles, California. The Battle of Monterrey took place in September of 1846. February 22, 1847 saw the battle of Buena Vista where General Taylor defeated the Mexicans under Antonio Lopez de Santa Anna, securing the conquest of California and New Mexico. The battles of Vera Cruz, Cerro Gordo, and then the Battle of Chapultepec (on the outskirts of Mexico City) followed as the U.S army under General Winfield Scott drove into the heart of Mexico (his invasion started on March 9, 1847).
The Treaty of Cahuenga, signed on January 13, 1847, ended the fighting in California. The Treaty of Guadalupe Hidalgo, signed on February 2, 1848, ended the War and gave the U.S. undisputed control of Texas as well as California and most of Arizona and New Mexico.
An interesting side note of the war was the Saint Patrick's Battalion (San Patricios), a group, approximately 500-strong, of (largely Irish-born) Americans who deserted the US Army in favor of the Mexican side. Many of them fought against what they alleged was brutal, racist discrimination received from the U.S. Many identified with Mexico as Catholics. They were hanged by the U.S.; making sure that the last thing these Irish men saw was the lowering of the Mexican flag and the raising of the U.S. flag as the war was won. Some historians claim that these men were prisoners of war. Other argue that they were traitors and deserters. There are many monuments to these soldiers in present-day Mexico.
The war can be considered a result of the belief in the Manifest Destiny doctrine by the US political class.