Bring a large pot of salted water to a boil. Add the dried spaghetti and cook according to the package instructions until al dente. Drain, reserving a cup of pasta water.
While the pasta cooks, heat the olive oil in a large skillet over medium heat. Add the garlic and sauté until just golden, about 1-2 minutes.
Add the diced onion and anchovies to the skillet, cooking until the onions are soft and the anchovies have dissolved, about 5 minutes.
Stir in the tinned cherry tomatoes along with the olives and capers. Reduce the heat and let simmer for about 10 minutes, or until the sauce thickens slightly.
Add the chili flakes, adjusting the quantity to achieve your desired level of heat.
Toss the cooked spaghetti with the sauce in the skillet, adding reserved pasta water as needed to loosen the sauce.
Stir in the chopped parsley and adjust seasoning with salt and pepper if necessary.
Serve hot, garnished with fresh basil leaves and optional grated cheese.