Invoking GraphQL APIs

API developed using GraphQL is normally provided a convenient UI Tools that can be used to test the API calls. there are various tools that can be used to build this as mentioned here.

You can easily enter the payload, Query Variables and HTTP Headers to invoke the API calls.

ref : https://anilist.co/graphiql

ref :

  • https://docs-search.hoteltrader.com/gui
  • https://hotel-trader.stoplight.io/docs/pull-api/ZG9jOjE0Njk0OTU0-overview

Also, you can use the Docs and Schema to see how is the API Structured before calling it.

Anyway, same calls can be done trough curl or any HTTP client (eg : Postman / Insomnia / Direct Java HTTP Client code ). You can use debug mode (F12) in the browser to see how is the request goes to back-end.

curl :

curl 'https://docs-search.hoteltrader.com/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://docs-search.hoteltrader.com' --data-binary '{"query":"# Write your query or mutation here\nquery getPropertiesByIds($SearchCriteriaByIds: SearchCriteriaByIdsInput) {\n  getPropertiesByIds(searchCriteriaByIds: $SearchCriteriaByIds) {\n  properties {\n      propertyId\n      propertyName\n      occupancies {\n        occupancyRefId\n        checkInDate\n        checkOutDate\n        numberOfAdults\n        numberOfChildren\n        childrenAges\n      }\n      rooms {\n        occupancyRefId\n        htIdentifier\n        roomName\n        shortDescription\n        longDescription\n       \n        rateInfo {\n          bar\n          binding\n          commissionable\n          commissionAmount\n          currency\n          netPrice\n          tax\n          grossPrice\n          payAtProperty\n          dailyPrice\n          dailyTax\n         \n          taxInfo {\n            payAtBooking {\n              date\n              name\n              description\n              value\n            }\n            payAtProperty {\n              date\n              name\n              description\n              value\n            }\n          }\n        }\n        mealplanOptions{\n          breakfastIncluded\n          lunchIncluded\n          dinnerIncluded\n          allInclusive\n          mealplanDescription\n        }\n        rateplanTag\n        refundable\n        cancellationPolicies {\n          startWindowTime\n          endWindowTime\n          cancellationCharge\n          timeZone\n        }\n      }\n\t\t\tshortDescription\n\t\t\tlongDescription\n      city\n      latitude\n      longitude\n      starRating\n      hotelImageUrl\n    }\n  }\n}","variables":{"SearchCriteriaByIds":{"propertyIds":[134388],"occupancies":[{"checkInDate":"2022-06-01","checkOutDate":"2022-06-02","numberOfAdults":2,"numberOfChildren":0,"childrenAges":""}]}}}' --compressed

Postman :

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.databind.ObjectMapper;

public class HotelTradeSearchTest {
	
	public static void main(String[] args) throws IOException {

		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendPOST() throws IOException {
		URL obj = new URL("https://docs-search.hoteltrader.com/graphql");
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/json");

		// For POST only - START
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(
				("{\n"
				+ "\n"
				+ "    \"operationName\":\"getPropertiesByCity\",\n"
				+ "    \"variables\":{\n"
				+ "        \"searchCriteriaByCity\":{\n"
				+ "            \"city\":\"New York, New York, United States Of America\",\n"
				+ "            \"occupancies\":[\n"
				+ "                {\n"
				+ "                    \"checkInDate\":\"2022-06-01\",\n"
				+ "                    \"checkOutDate\":\"2022-06-02\",\n"
				+ "                    \"numberOfAdults\":2,\n"
				+ "                    \"numberOfChildren\":0,\n"
				+ "                    \"childrenAges\":\"\"\n"
				+ "                }\n"
				+ "            ]\n"
				+ "        }\n"
				+ "    },\n"
				+ "    \"query\":\"query getPropertiesByCity($searchCriteriaByCity: SearchCriteriaByCityInput) {\\n getPropertiesByCity(searchCriteriaByCity: $searchCriteriaByCity) {\\n properties {\\n propertyId\\n propertyName\\n occupancies {\\n occupancyRefId\\n checkInDate\\n checkOutDate\\n numberOfAdults\\n numberOfChildren\\n childrenAges\\n }\\n rooms {\\n occupancyRefId\\n htIdentifier\\n roomName\\n shortDescription\\n longDescription\\n rateInfo {\\n bar\\n binding\\n commissionable\\n commissionAmount\\n currency\\n netPrice\\n tax\\n grossPrice\\n payAtProperty\\n dailyPrice\\n dailyTax\\n taxInfo {\\n payAtBooking {\\n date\\n name\\n description\\n value\\n }\\n payAtProperty {\\n date\\n name\\n description\\n value\\n }\\n }\\n }\\n mealplanOptions {\\n breakfastIncluded\\n lunchIncluded\\n dinnerIncluded\\n allInclusive\\n mealplanDescription\\n }\\n rateplanTag\\n refundable\\n cancellationPolicies {\\n startWindowTime\\n endWindowTime\\n cancellationCharge\\n timeZone\\n }\\n }\\n shortDescription\\n longDescription\\n city\\n latitude\\n longitude\\n starRating\\n hotelImageUrl\\n }\\n }\\n}\\n\"\n"
				+ "\n"
				+ "}").getBytes()
				);
		os.flush();
		os.close();
		// For POST only - END

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);

		if (responseCode == HttpURLConnection.HTTP_OK) { // success
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			ObjectMapper mapper = new ObjectMapper();
			System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(response.toString())));
			
		} else {
			System.out.println("POST request not worked");
		}
	}
}

Maven dependencies:

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.11.2</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.2</version>
		</dependency>

References :

  • https://www.graphql-java.com/
  • https://www.baeldung.com/spring-graphql
  • https://www.howtographql.com/graphql-java/0-introduction/
  • https://developer.okta.com/blog/2020/01/31/java-graphql
  • https://github.com/graphql-java/graphql-java
  • https://github.com/graphql-java/tutorials/tree/master/book-details
  • https://www.programcreek.com/java-api-examples/?api=graphql.schema.idl.RuntimeWiring
  • https://www.tabnine.com/code/java/classes/graphql.schema.idl.RuntimeWiring
  • https://search.maven.org/artifact/com.graphql-java/graphql-java/16.2/jar
  • http://www.java2s.com/example/jar/g/download-graphqljava40jar-file.html
  • https://graphql.org/code/#generic-tools

#apis, #graphql, #java, #rest