This tutorial uses the Face Analyzer API. See the docs, live demo, and pricing.
If your app has to confirm that the person holding the phone is the person on the ID card, or that today's check-in selfie matches the photo enrolled last month, you need a face comparison API: send two images, get back whether they show the same person. This guide uses the Face Analyzer API to compare two faces in one call from Python, cURL and JavaScript, read the response correctly, and turn it into a verify decision you can ship. When you need to find one person among many enrolled users, the last part shows the repository search that adds a similarity score.
Compare Two Faces in One API Call
The /compare-faces endpoint takes a source_image (the reference face, for example the ID photo) and a target_image (the photo to check, for example the selfie). Both are sent as multipart file uploads. The response tells you which faces in the target belong to the source person.
cURL
curl -X POST "https://faceanalyzer-ai.p.rapidapi.com/compare-faces" \
-H "x-rapidapi-key: YOUR_API_KEY" \
-H "x-rapidapi-host: faceanalyzer-ai.p.rapidapi.com" \
-F "source_image=@id_photo.jpg" \
-F "target_image=@selfie.jpg"Python
import requests
URL = "https://faceanalyzer-ai.p.rapidapi.com/compare-faces"
HEADERS = {
"x-rapidapi-host": "faceanalyzer-ai.p.rapidapi.com",
"x-rapidapi-key": "YOUR_API_KEY",
}
with open("id_photo.jpg", "rb") as src, open("selfie.jpg", "rb") as tgt:
response = requests.post(
URL,
headers=HEADERS,
files={"source_image": src, "target_image": tgt},
)
body = response.json()["body"]
print(len(body["matchedFaces"]), "matched,", len(body["unmatchedFaces"]), "unmatched")
# 1 matched, 0 unmatchedJavaScript (Node.js 18+)
import { readFile } from "node:fs/promises";
const form = new FormData();
form.append("source_image", new Blob([await readFile("id_photo.jpg")]), "id_photo.jpg");
form.append("target_image", new Blob([await readFile("selfie.jpg")]), "selfie.jpg");
const response = await fetch("https://faceanalyzer-ai.p.rapidapi.com/compare-faces", {
method: "POST",
headers: {
"x-rapidapi-host": "faceanalyzer-ai.p.rapidapi.com",
"x-rapidapi-key": "YOUR_API_KEY",
},
body: form,
});
const { body } = await response.json();
console.log(body.matchedFaces.length > 0 ? "MATCH" : "NO MATCH");Comparing Images by URL
If both photos already live on a public URL (an S3 bucket, a CDN), skip the upload and pass source_image_url and target_image_url as form fields. The endpoint accepts application/x-www-form-urlencoded or multipart, not a JSON body, and you can mix the two styles (a file for the source, a URL for the target).
response = requests.post(
URL,
headers=HEADERS,
data={
"source_image_url": "https://example.com/id_photo.jpg",
"target_image_url": "https://example.com/selfie.jpg",
},
)
print(response.json()["body"]["matchedFaces"] != []) # TrueBuilding in JavaScript instead? The face-api.js alternative guide makes the same comparison from Node.js with built-in fetch and FormData.
Reading the Response: matchedFaces vs unmatchedFaces
The API looks for the face in the source image, then checks every face it finds in the target image. Each target face lands in one of two lists:
matchedFaces: faces that belong to the same person as the source face.unmatchedFaces: faces of anyone else.
Every entry carries a boundingBox (topLeft and bottomRight, normalized from 0 to 1 against the target image size) and landmarks for the eyes, nose and mouth. Multiply the box by the image width and height to draw it. Here is a real result where the target photo contains two people (two photos stitched side by side into one image):

/compare-faces output: one face in matchedFaces, one in unmatchedFaces, boxes drawn from the returned coordinates.Two details matter in production. The endpoint makes the match decision for you, so there is no score threshold to tune: a face is either matched or unmatched. And when no usable face is found in either image, both lists come back empty, so check both lists and ask the user for a new photo in that case.
| matchedFaces | unmatchedFaces | Meaning | What to do |
|---|---|---|---|
| 1 | 0 | Same person | Accept |
| 0 | 1 | Different person | Reject or send to review |
| 0 | 0 | No usable face | Ask for a new photo |
| any | total above 1 | Several people in the target | Ask for a solo photo |
Face Verification Logic You Can Ship
For a 1:1 face verification flow (selfie against ID, check-in selfie against the enrolled photo), wrap the call in a function that returns one of four outcomes instead of a bare boolean. Your UI can then show the right message: retake the photo, step away from friends, or send the case to manual review.
def verify(source_path, target_path):
with open(source_path, "rb") as src, open(target_path, "rb") as tgt:
response = requests.post(
URL,
headers=HEADERS,
files={"source_image": src, "target_image": tgt},
)
body = response.json()["body"]
matched = len(body["matchedFaces"])
unmatched = len(body["unmatchedFaces"])
if matched == 0 and unmatched == 0:
return "NO_FACE" # no usable face found: ask for a new photo
if matched + unmatched > 1:
return "MULTIPLE_FACES" # a selfie should show exactly one person
return "MATCH" if matched == 1 else "NO_MATCH"
print(verify("id_photo.jpg", "selfie.jpg")) # MATCH
print(verify("id_photo.jpg", "stranger.jpg")) # NO_MATCH
print(verify("id_photo.jpg", "landscape.jpg")) # NO_FACE
print(verify("id_photo.jpg", "two_people.jpg")) # MULTIPLE_FACESThese four lines of output are the real results we got on our test photos. Keep the source image to a single face too: in our tests, when the source contained two people the API compared using the larger face, which is rarely what you want on an ID card next to a hand or a second photo. Crop the source to the face you mean.
When You Need a Similarity Score: 1:N Face Search
/compare-faces is built for 1:1 checks where you already hold both images. For access control, event check-in or attendance you usually have one new photo and a list of known people. That is a 1:N problem: enroll each person once in a facial repository, then search new photos against it. The search response includes a Similarity from 0 to 100, so you can choose your own threshold.
import requests
BASE = "https://faceanalyzer-ai.p.rapidapi.com"
HEADERS = {
"x-rapidapi-host": "faceanalyzer-ai.p.rapidapi.com",
"x-rapidapi-key": "YOUR_API_KEY",
}
# 1. Create a repository once
requests.post(
f"{BASE}/create-facial-repository",
headers=HEADERS,
data={"repository_id": "office-access"},
)
# 2. Enroll each authorized person with your own ID
with open("id_photo.jpg", "rb") as f:
requests.post(
f"{BASE}/save-face-in-repository",
headers=HEADERS,
files={"image": f},
data={"repository_id": "office-access", "external_id": "employee-001", "max_faces": "1"},
)
# 3. Search a new photo against everyone enrolled
with open("selfie.jpg", "rb") as f:
response = requests.post(
f"{BASE}/search-face-in-repository",
headers=HEADERS,
files={"image": f},
data={"repository_id": "office-access"},
)
matches = response.json()["body"]["FaceMatches"]
THRESHOLD = 90 # Similarity is 0 to 100
if matches and matches[0]["Similarity"] >= THRESHOLD:
print("ACCESS GRANTED:", matches[0]["ExternalImageId"], round(matches[0]["Similarity"], 2))
else:
print("ACCESS DENIED")
# ACCESS GRANTED: employee-001 99.96Each entry in FaceMatches holds the ExternalImageId you enrolled, its FaceId, the Similarity and a BoundingBox. A person who was never enrolled returns an empty FaceMatches list. Our same-person pair above scored 99.96. Start around 90 for doors and internal tools, go higher for anything that moves money, and validate the threshold on a sample of your own users before you lock it in. Use GET /list-repository-faces to audit who is enrolled and /delete-face-from-repository to remove someone who leaves.
Face Comparison Use Cases
KYC: Selfie vs ID Document
The classic 1:1 case. The user uploads an ID, takes a selfie, and you run /compare-faces with the ID photo as source. Crop the portrait out of the ID first, since it is small and sits next to text. The identity verification guide covers the whole flow, and the eKYC tutorial for SaaS onboarding adds reading the ID fields.
Access Control and Event Check-In
Enroll staff or attendees in a repository, then search each camera capture at the door or the registration desk. Unknown faces come back empty and can trigger a badge or PIN fallback. Log every attempt with the matched ID and similarity for audits.
Attendance and Shift Clock-In
The same 1:N search, repeated every morning: it stops buddy punching without extra hardware. See the face recognition attendance system in Python for a complete script.
Duplicate Account Detection
Marketplaces and promo-heavy apps search every new signup selfie against existing users to catch the same person opening a second account. It is the repository search run in reverse: a match is the red flag. The full signup flow, with measured similarity scores, is in the duplicate account detection guide.
Exam Proctoring
Compare the student at the start of the exam with the enrolled photo, then repeat the check at random intervals and flag mismatches for a human to review.
Production Tips for Face Matching
- More than one face in the frame. A friend in the background turns a clean match into an ambiguous result. Reject targets with more than one face for verification flows, as the function above does.
- Tiny or low-quality reference faces. ID portraits are small and often printed on textured backgrounds. Crop tightly around the face before sending it, and prefer the highest resolution scan you have.
- Lighting, angle and accessories. Guide users toward a front-facing, evenly lit selfie without heavy sunglasses for the cleanest match.
- Pair identity with liveness. A match confirms identity. For onboarding, payments or door access, add a liveness step so you also confirm a live person is present.
- Keeping biometric data longer than needed. Faces are biometric data under GDPR and similar laws. Get consent before enrolling anyone, document retention, and delete repository entries when the user leaves.
If you want to understand what happens under the hood (detection, face encoding, distance between embeddings), the face matching walkthrough breaks it down step by step, and the face recognition API comparison lines up the main providers if you are still choosing.
A face comparison API turns "is this the same person?" into one HTTP call, and the decision logic above handles the cases that break naive integrations. Grab a free key on the Face Analyzer API page, run the verify() function on an ID photo and a selfie of your own, and you will have a working 1:1 check in a few minutes.
Frequently Asked Questions
- What does a face comparison API return?
- The compare-faces endpoint returns two lists for the target image: matchedFaces (faces that belong to the person in the source image) and unmatchedFaces (everyone else), each with a normalized bounding box and eye, nose and mouth landmarks. The endpoint makes the match decision for you, so there is no threshold to tune. When you want a 0 to 100 Similarity score per match, enroll the reference photo in a facial repository and use the search endpoint.
- How do I verify that a selfie matches an ID photo?
- Send the ID photo as source_image and the selfie as target_image. Treat the result as a match when matchedFaces has exactly one entry and unmatchedFaces is empty. Two empty lists mean no usable face was found, so ask the user for a new photo instead of rejecting them.
- Should I add a liveness check to face comparison?
- For onboarding, payments or door access, yes. Face comparison confirms that two faces belong to the same person; a liveness step (a blink or head-turn challenge, or a dedicated liveness provider) also confirms that a live person is in front of the camera. Together they make a complete verification flow.



