According to the Spanish media, there were 24 troops and two interpreters remaining in the South Asian country.
"Today is an important day in our modern history .... History consists of the deeds of great heroes, but also of the actions of anonymous heroes who, with their solidarity ... defend democratic values in the world," Defense Minister Margarita Robles said.
The troops were welcomed by King Felipe VI, Prime Minister Pedro Sanchez and Robles at the Torrejon Air Base near Madrid.
Overall, some 27,000 Spanish servicemen have been deployed to Afghanistan since 2002. Of those, 100 have died, including 62 in a plane crash in Turkey on their way home in 2003.
The United States and its NATO allies launched the operation in Afghanistan in 2001. In April, US President Joe Biden declared that the United States would begin withdrawing its troops, starting May 1. Since then, all other NATO members announced withdrawing their forces as well.