I'm trying to invoke the mongodb atlas api using java, I'm getting a 400 bad request error,Details

I’m trying to invoke mongodb atlas rest api to create atlas search indexes, I tried the request in postman and it works fine, I have written the following Java code but is getting a 400 bad request error, Any idea if im missing anything here?

    URI uri = URI.create("https://cloud.mongodb" +
            ".com/api/atlas/v1.0/groups/5f6f561e246090346809ec1c/clusters/wso2-apim-cluster/fts/indexes/");

    HttpPost post = new HttpPost(uri);
    Gson gson = new Gson();
    Map<String, String> map = new HashMap<>();
    Map<String, String> mappings = new HashMap<>();
    mappings.put("dynamic", "true");

    map.put("collectionName", "test");
    map.put("database", "randomDb");
    map.put("mappings", gson.toJson(mappings));
    map.put("name", "default");


    try {
        HttpEntity stringEntity = new StringEntity(gson.toJson(map));
        post.setEntity(stringEntity);

        DigestScheme md5Auth = new DigestScheme();
        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse authResponse = client.execute(new HttpGet(uri));
        final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0];
        md5Auth.processChallenge(challenge);
        final Header solution = md5Auth.authenticate(
                new UsernamePasswordCredentials("", ""),
                post
        );

        md5Auth.createCnonce();
        post.addHeader("content-type", "application/json");
        post.addHeader(solution.getName(), solution.getValue());
        HttpResponse execute = client.execute(post);
        System.out.println(execute.getStatusLine());

        for (Header h : execute.getAllHeaders()
             ) {
            System.out.println(h.getName());
            System.out.println(h.getValue());
            System.out.println();

        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MalformedChallengeException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    }

Managed to solve this issue, problem was passing a json string for mappings part of the body, changed as follows

    Map<String, Object> map = new HashMap<>();
    Map<String, Object> mappings = new HashMap<>();
    mappings.put("dynamic", true);

    map.put("collectionName", "col1");
    map.put("database", "abc");
    map.put("mappings", mappings);
    map.put("name", "default");

Everything else remained same, hope this helps someone :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.