Marketo REST API Java实现:通过邮箱查询并删除线索
Hey there! I’ve worked with Marketo’s REST API quite a bit, so I can help you out with querying leads by email and deleting them via Java. Let’s break this down step by step:
Marketo’s REST API absolutely supports filtering leads by email—you just need to use the right parameters with the Leads endpoint. Here’s how to do it:
API Basics
Use the GET /rest/v1/leads.json endpoint with these key parameters:
filterType=email: Tells Marketo you’re filtering on the email fieldfilterValues: Comma-separated list of emails you want to look up (e.g.,john@doe.com,jane@doe.com)fields: Optional, but useful to limit returned data (e.g.,id,emailto only get lead IDs and emails for deletion)
Java Implementation (Using OkHttp for Simplicity)
First, add the OkHttp dependency to your Maven project:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.10.0</version> </dependency>
Code to Fetch Leads by Email
This example includes fetching the required access token first (Marketo uses OAuth 2.0 for authentication):
import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class MarketoLeadManager { // Replace these with your Marketo instance details private static final String MARKETO_BASE_URL = "https://your-instance-id.mktorest.com"; private static final String CLIENT_ID = "your-client-id"; private static final String CLIENT_SECRET = "your-client-secret"; public static void main(String[] args) throws IOException { // Step 1: Get OAuth access token String accessToken = fetchAccessToken(); // Step 2: Query leads by email String targetEmail = "example@test.com"; String leadResponse = queryLeadsByEmail(accessToken, targetEmail); System.out.println("Fetched leads: " + leadResponse); // We'll parse this response to get lead IDs next } private static String fetchAccessToken() throws IOException { String tokenUrl = String.format("%s/oauth/token?grant_type=client_credentials&client_id=%s&client_secret=%s", MARKETO_BASE_URL, CLIENT_ID, CLIENT_SECRET); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(tokenUrl).build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Failed to fetch token: " + response); // Quick parse for access token (use Jackson/Gson for production code) String responseBody = response.body().string(); return responseBody.split("\"access_token\":\"")[1].split("\"")[0]; } } private static String queryLeadsByEmail(String accessToken, String email) throws IOException { String queryUrl = String.format("%s/rest/v1/leads.json?filterType=email&filterValues=%s&fields=id,email&access_token=%s", MARKETO_BASE_URL, email, accessToken); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(queryUrl).build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Failed to query leads: " + response); return response.body().string(); } } }
Once you have the lead IDs from the query response, use Marketo’s POST /rest/v1/leads/delete.json endpoint to remove them.
Add Jackson for JSON Parsing
To parse the lead response and extract IDs, add Jackson to your Maven dependencies:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
Code to Delete Leads
Add this method to the MarketoLeadManager class, and update the main method to use it:
import okhttp3.MediaType; import okhttp3.RequestBody; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; // ... existing code ... public static void deleteLeads(String accessToken, List<Integer> leadIds) throws IOException { String deleteUrl = String.format("%s/rest/v1/leads/delete.json?access_token=%s", MARKETO_BASE_URL, accessToken); // Build JSON request body with lead IDs String jsonBody = String.format("{\"input\":[%s]}", leadIds.stream().map(String::valueOf).collect(Collectors.joining(","))); RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8")); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(deleteUrl) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Failed to delete leads: " + response); System.out.println("Deletion result: " + response.body().string()); } } // Update main method to parse leads and delete public static void main(String[] args) throws IOException { String accessToken = fetchAccessToken(); String targetEmail = "example@test.com"; String leadResponse = queryLeadsByEmail(accessToken, targetEmail); // Parse lead IDs from response ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(leadResponse); JsonNode resultNode = rootNode.get("result"); List<Integer> leadIds = new ArrayList<>(); for (JsonNode lead : resultNode) { leadIds.add(lead.get("id").asInt()); } // Delete leads if any were found if (!leadIds.isEmpty()) { deleteLeads(accessToken, leadIds); } else { System.out.println("No leads found matching the email."); } }
- Permissions: Make sure your Marketo API user has
Read LeadandDelete Leadpermissions—otherwise you’ll get 403 errors. - Rate Limits: Marketo enforces API rate limits, so if you’re processing large batches, add delays or use batch endpoints to avoid being throttled.
- Irreversible Action: Deleting leads is permanent! Always test the query first to confirm you’re targeting the right leads before deleting.
- Batch Queries: To look up multiple emails at once, separate them with commas in the
filterValuesparameter (e.g.,filterValues=email1@test.com,email2@test.com).
内容的提问来源于stack exchange,提问作者MintMelt

