Skip to content

Instantly share code, notes, and snippets.

@mekarpeles
Created May 22, 2024 15:58
Show Gist options
  • Save mekarpeles/0d308bfd8e75858d2266b8aa983cac07 to your computer and use it in GitHub Desktop.
Save mekarpeles/0d308bfd8e75858d2266b8aa983cac07 to your computer and use it in GitHub Desktop.
js example of adding app identification headers to openlibrary.org API calls
const url = "https://openlibrary.org/search.json?q=test";
const headers = new Headers({
"User-Agent": "MyAppName/1.0 ([email protected])"
});
const options = {
method: 'GET',
headers: headers
};
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
@LyudmilC-dacc-939
Copy link

Hello, I wrote an email to sapphire regarding a small inconvenience I'm having, is there any chance you CAN write such form for Java(I need it for a personal project that is going to make real requests/calls to your APIs)? It's quite a primitive Java code that I have to use public API and wanted to use this one.

@mekarpeles
Copy link
Author

It's a network request so you should be able to adapt this to any language.

@katusiimeconrad
Copy link

katusiimeconrad commented Aug 26, 2024

While using Native Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

public class OpenLibraryClient {

    public static void main(String[] args) {
        String url = "https://openlibrary.org/search.json?q=test";
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "MyAppName/1.0 ([email protected])");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String response = in.lines().collect(Collectors.joining());
                in.close();
                System.out.println("Response: " + response);
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You can look into HttpClients such as Okhttp as well which simplify working with requests, to something like this:

import okhttp3.*;

import java.io.IOException;

public class OpenLibraryClient {

    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) {
        String url = "https://openlibrary-graphql.onrender.com/graphql";
        String query = "{ \"query\": \"{ findBookISBN(id: 9780140328721) { title authors { key } } }\" }";
        try {
            String response = sendGraphQLRequest(url, query);
            System.out.println("Response: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String sendGraphQLRequest(String url, String query) throws IOException {
        RequestBody body = RequestBody.create(query, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("User-Agent", "MyAppName/1.0 ([email protected])")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }
}

@LyudmilC-dacc-939
Copy link

@katusiimeconrad Wow man, many thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment