Examine the possible consequences. They include lawsuits and loss of your earnest money, also called good-faith money. Aside from keeping your earnest money, the sellers may also seek damages for lost time on the market and perhaps other considerations.
The seller's agent and buyer's agent may also seek damages. They brought about a meeting of the minds and are entitled to their commissions. Are they likely to do that? Probably not, but they can. Even if they do and lose, you'll have defense expenses.
Use the attorney-approval clause, if there is one and if it's not too late. Real estate contracts usually contain a clause that allows both parties to have an attorney look it over and approve of it within a specified number of days, usually three to five.Tell your lawyer you want out.
Check the contract contingencies. They may offer a way out. For example, you do not have to agree to buy a house if the inspection was unsatisfactory, but you have to say so in writing within a specified number of days.
If the bank won't give you the mortgage because of underwriting changes, or because something about your situation changed or because the house did not appraise for the amount you need to finance, you can get out of the contract. All bar-approved contracts have a financing contingency. You will need a letter of denial from the bank.
Bear in mind that you are not a lawyer. By looking over the contingencies, you are only doing your homework.
Contact your buyer's agent, if you have one. Your buyer's agent will have some questions and will either pursue the problem for you or tell you to see your lawyer. If it's simply a matter of presenting an unsatisfactory inspection report or telling the other party that your bank declined to give you a mortgage, the agent will do it. If it's anything that is not black and white, the agent will refer you to your lawyer.
Ask your buyer's agent or, if you don't have a buyer's agent, the seller's agent to inform the other party that you would like to get out of the contract. Even if you don't have grounds, if you're reasonable and polite, it might work. The seller is not going to like it but will also be thinking about the cost of a lawsuit. No one likes to get into litigation. If the market is good and you are very lucky, the seller might agree.
Contact your real estate lawyer if you do not have a buyer's agent or if your buyer's agent advises you to do so.
Accept that you will lose your earnest money and say so. That may go a long way toward preventing a lawsuit.