How did Scientists Capture The First Images of Molecules Before and After Reaction?
There are a ton of papers on how AFM works, but I'll have a go at explaining it anyhow.

Atomic Force Microscopy (AFM) is a venerable technology for imaging nanostructures down to individual molecules by physically contacting atoms on surfaces. The whole process is very similar to a finger reading Braille.

What does it mean to physically contact an atom? It means that the AFM works by detecting some kind of repulsion between an atom and a very, very sharp probe due to their respective electron clouds repelling. The forces between surfaces on the nanoscale are a complicated mixture of attraction due to Casimir-Polder/Van der Waals interactions, dipole-dipole interactions, electrostatic repulsion, Pauli exclusion, etc. etc., but the key point is that if two objects get too close together they will experience a rapidly increasing repulsive interaction, which the AFM picks up.

This repulsion is detected through the deflection of a cantilever (a thin, long, elastic beam of material). The probe is mounted on the end of this cantilever, and the cantilever bends when the probe is pushed up against a substrate. The deflection of this cantilever is measured by bouncing a laser beam off the end, the change in position of the reflected beam indicating the force.

The AFM probe has an atomically sharp tip that can localise single atoms on a surface, and the tip is moved around using exquisitely precise actuators so that the tip can be scanned back and forth over a surface, picking up the bumps and valleys of the sample that indicate the positions of atoms. I've seen ads for AFM probes that actually have flared tips - these can obtain even more 3D information about nanostructures as they can hook into nanostructures from the side and measure the texture and relief parallel to the surface.