Before the unification of China by the First Emperor in 221 BC, Beijing had been, for centuries, the capital of the ancient states of Ji and Yan.
During the first millennia of imperial rule, it was a provincial city in northern China. Its stature grew in the 10th to 13th centuries when the nomadic Khitan and forest-dwelling Jurchen peoples from beyond the Great Wall expanded southward and made the city a capital of their dynasties, the Liao and Jin.
Beijing as a capital for the whole of China grew out of the Yuan (Mongol) capital Dadu or Khanbaliq. The Ming moved their capital there from Nanjing in 1421.
The walls in the photographs below, built under the Ming, are those of the Inner City. Under the Manchu or Qing Dynasty rulers (1644-1912), it came to be called the Tartar City, in the loose sense of Tartar, because only Manchus were allowed to live there.
The Han Chinese, whose businesses depended on the imperial households, lived in the Outer City, which had its own wall.
Historical names of Beijing (Wikipedia).
The Inner and Outer walls were damaged during the Boxer Rebellion, punctured in various places after 1911 and almost entirely dismantled by the Communists.
Tiananmen Square lies between Tiananmen Gate, the gate into the Imperial City, and Zhengyangmen or Qianmen Gate, the gate into the Outer City.
Walls of the Tartar City via visualisingchina.net: