You can use the Dot Product for this. Passing a normalized direction vector into the Dot Product along with another vector will resurn a scalar value representing the element of the vector that is in the direction of the direction vector. Multiplying the normalized direction vector by the acalar value will give you your closest point.
Consider 3 points - O (the origin), A (the end point of the line), and B (the point you want to get closest to along the line). You want the point on the line that is closest to B - lets call thay C.
Start with the vector OA and normalize it (make it 1 unit length. The result defines the direction of the line.
Calculate the Dot Product of that Direction Vector with the vector OB to produce the scalar distance to the closest point.
Multiply the Direction Vector by the scalar distance to produce the vector to the closest point - ie, OC.
EDIT : Thanks to @batFINGER for the following example Python code :
from mathutils import Vector
# two points define the line
a, b = Vector((0.0,0.0,0.0)), Vector((1.0,1.0,1.0))
p = Vector((0.0,0.2,0.5))
n = (b - a).normalized()
ap = p - a
t = ap.dot(n)
x = a + t * n # x is a point on line
print("point on line :", x)
print("distance from p:", (p - x).length)
# cross product for distance
d = ap.cross(n).length
print("dist cross prod:", d)
Also see https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation