How Switzerland became a country?

The Swiss Confederation was founded in 1291. At that time it was an agreement for mutual self-defence between 4 small mountain cantons (states) within the German Empire who wanted to defend themselves from takeover by more powerful states and feudal rulers within the empire.
Over the next few centuries Switzerland grew as new territories joined. It gradually became effectively a group of independent countries, but legally they were all parts of the German Empire.

In 1648, at a peace treaty after the 30 years war, the German Empire finally recognised that the members of the Swiss Confederation were not part of the empire.

This continued until Napoleon invaded. He annexed parts of Switzerland and turned the rest into a client state.
The previous state (many independent cantons) was re-instated in 1815.

It was only in 1848 that the members of the Swiss confederation agreed to form a federal state and have a permanent federal government. This is when Switzerland became one country.