This is my understanding which I had posted in some other fourm. I wish to share it here too.
He (swt) says: “I have only created jinns and humans to follow my command. I do not need from them to provide for Me, and I do not need from them to feed Me. Allah is surely the One Who gives providence, and He is the Mighty and Strong.” The Holy Qur’an, Chapter 51, Verses 56-58
{He it is Who created the heavens and the earth in six Days—and His Throne was over the waters—that He might try you, which of you is best in conduct…} (Hud 11:7)
And again,
{He Who created Death and Life, that He may try which of you is best in deed: and He is the Exalted in Might, Oft-Forgiving} (Al-Mulk 67:2)
So Allah created us to follow his command and to test us if we are going to follow his command or not.
Your next question will be why did he want to test us ?
My thoughts on this question, based on my limited study and knowledge of our religion, are:
Allah created trillions and trillions of things in this universe who have no freewill and are following his command and will keep on following those commands till he wants them to e.g , stars, moons, trees, angels etc. Allah knows the outcome of their behavior.
Then he created Jins who had free will but they went stray and created havoc so they got wiped out with the will of Allah.
Then Allah replaced Jins with humans with free will and He gave us rasools and books.
The questions is still un answered why he wants to test us ?
So Allah has all kinds of attributes , one of them is that he knows everything. But if he does not want to know the outcome of anything in advance and wants to test something and then know the outcome he has the power to do so. After all he has all kinds of powers. Therefore in our case he did not want to know the outcome of our behavior in advance and wanted to test us therefore he created us with free will , he gave us his rasools and his books to test the outcome and decide our fate based on our behavior in this universe.
Wallah alim bis sawab.