Scholars might debate a bit about the primary purpose of a medieval city, but we can certainly say that medieval cities became the hubs of trade and of the economy during that era as craftsmen gathered together and markets and fairs sprang up to allow people to sell their wares. Let's look at this in more detail.
Medieval cities were quite small by modern standards, and they were usually surrounded by defensive walls that protected the city from enemies but also drew a sharp line of demarcation between city and country. But people didn't usually live in a city for the sake of defense (although this was certainly handy when enemies threatened).
Rather, people went to medieval cities to buy and sell. Craftsmen moved to cities to find a steady market in which to sell their goods, and they joined guilds to support one another. These artisans had small shops at street level and lived upstairs, and they practiced all kinds of trades, from shoemaker to baker to apothecary. Traveling merchants arrived in cities looking for buyers and sellers and giving their business to taverns and inns. Most cities were built along waterways for easier movement and shipping of goods (as well as sanitary needs), and roads sprang up to connect towns and cities. Even the country peasants came to town. They sold their crops at markets or found entertainment in fairs and events. Some moved to cities permanently, hoping to find a better, more prosperous life. Sometimes they did. More often they didn't.
Medieval cities could also be spiritual centers, especially towns that grew up around cathedrals. Pilgrims flocked to those cathedrals, and they spent plenty of money while doing so (emphasizing the economic purpose of cities again).