Yes definitly
It is legal, there is no law that says you have to buy electricity from the city... the thing is you might not want to be 100% off the grid... typically it's cheaper for you to sell the electricity back to the city and use it when you don't generate enough electricity... otherwise you have to invest in energy storage devices which can cost you a lot of money.
You just need an inverter and any extra energy you don't use gets put back onto the grid and your meter rolls backwards.