Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.

Java and API-NG

This page contains some code snippets of Java interaction with API-NG. The This example shows how to use Java to send requests to get a list of markets, then the list of runners for the chosen market and finally how to place a bet.list the event types, find the next horse racing market and then placing a bet with an invalid stake to trigger an error. The code referred to here is available at

In the sample code we demonstrate both use the json-rpc and REST rescript protocols. All requests are handled in the sent and received using json format. To post a request we prepare the json string using Java objects and then we serialize the object using the gson library. The example requests contain some predefined data that can be modified depends on user needs.  The "operations" object is an instance of ApiNgOperations, that implements some wrapper methods for the APING operations. We send the filter data, app key and the session token. The method prepares the params for the request and then calls the method makeRequest that gets a json string, that is the actual request body, and posts the request to the API-NG endpoint.


This is a maven project containing Java sample code to connect to the Betfair API-NG application.
It requires:
  - Apache Maven 3
  - Java 7

How to run it

You first build the project with:
mvn clean package

You can again use Apache Maven to run the application passing the app key, session token and the method (json-rpc or rescript):
mvn exec:java -Dexec.mainClass="com.betfair.aping.ApiNGDemo" -Dexec.args="<YOUR APP KEY> <YOUR SESSION TOKEN> <METHOD>"

<YOUR APP KEY>: a valid app key
<YOUR SESSION TOKEN>: a valid Betfair session token
<METHOD>: json-rpc or rescript

example: mvn exec:java -Dexec.mainClass="com.betfair.aping.ApiNGDemo" -Dexec.args="myAppKey mySessionToken json-rpc"

Code Snippet

Creating the request - JSON-RPC

Code Block
private String makeRequest(String operation, Map<String, Object> params, String appKey, String ssoToken, boolean jsoRpc) {
String requestString;
          //Handling the JSON-RPC request
      JsonrpcRequest request = new JsonrpcRequest();
      request.setMethod(ApiNGDemo.getProp().getProperty("SPORTS_APING_V1_0") + operation);

requestString  JsonConverter.convertToJson(request);
      request.setParams(params   System.out.println("\nRequest: "+requestString);

//We need to pass the "sendPostRequest" method a string in util format:  requestString
HttpUtil requester =  JsonConverter.convertToJson(request);
} else {
new HttpUtil();
return requester.sendPostRequestJsonRpc(requestString, operation, appKey, ssoToken);

Creating the request - Rescript

Code Block
String requestString;
        //Handling the RESTRescript request
        params.put("id", 1);

        requestString =  JsonConverter.convertToJson(params);

            System.out.println("\nRequest: "+requestString);

        //We need to pass the "sendPostRequest" method a string in jsonutil format:  requestString
        HttpUtil requester = new HttpUtil();
return        String response = requester.sendPostRequestsendPostRequestRescript(requestString, operation, appKey, ssoToken);


        if(response != null)
            return response;
            throw new APINGException();

Calling API-NG

Code Block
String jsonRequest = param;
HttpPost post = new HttpPost(composeUrl(ApiNGDemo.isJsonRpcrequest(), operation)URL);
	String responseStringresp = null;
	try {
		            post.setHeader(HTTP_HEADER_CONTENT_TYPE, ApiNGDemo.getProp().getProperty("APPLICATION_JSON"));
		            post.setHeader(HTTP_HEADER_ACCEPT, ApiNGDemo.getProp().getProperty("APPLICATION_JSON"));
		            post.setHeader(HTTP_HEADER_ACCEPT_CHARSET, ApiNGDemo.getProp().getProperty("ENCODING_UTF8"));
		            post.setHeader(HTTP_HEADER_X_APPLICATION, appKey);
		            post.setHeader(HTTP_HEADER_X_AUTHENTICATION, ssoToken);

		            post.setEntity(new StringEntity(jsonRequest, ApiNGDemo.getProp().getProperty("ENCODING_UTF8")));
            HttpClient httpClient = new DefaultHttpClient();
		ResponseHandler<String> handler = new JsonResponseHandler();

            HttpParams httpParams = httpClient.getParams();
		            HttpConnectionParams.setConnectionTimeout(httpParams, new Integer(ApiNGDemo.getProp().getProperty("TIMEOUT")).intValue());
		            HttpConnectionParams.setSoTimeout(httpParams, new Integer(ApiNGDemo.getProp().getProperty("TIMEOUT")).intValue());

		responseString            resp = httpClient.execute(post, handler);

Code Snippets


        } catch (UnsupportedEncodingException e1) {
            //Do something

        } catch (ClientProtocolException e) {
            //Do something

        } catch (IOException ioE){
            //Do something


        return resp;

Find Horse Racing event type id

To invoke listEventTypes we need to pass a marketFilter. In this case we set the "text query" to "Horse Racing".

Code Block
MarketFilter marketFilter;
            marketFilter = new MarketFilter();
marketFilter.setTextQuery("Horse Racing");
            Set<String> eventTypeIds = new HashSet<String>();

            System.out.println("1.(listEventTypes) Get all Event Types...\n");
            List<EventTypeResult> r = operationsjsonOperations.listEventTypes(marketFilter, applicationKey, sessionToken);
            System.out.println("2. Extract Event Type Id for Horse Racing...\n");
            for (EventTypeResult eventTypeResult : r) {
                if(eventTypeResult.getEventType().getName().equals("Horse Racing")){
                     System.out.println("Found the market type3. EventTypeId for \"Horse Racing\" is: " + eventTypeResult.getEventType().toStringgetId()+"\n");

Get next available horse races


To invoke listMarketCatalogue we need to pass:

  • marketFilter.where we set the event type = 7 (that is the "Horse Racing" market event type id), and the Market Start Time
  • marketProject to set the type and amount of data returned about the market
  • marketSort, to choose how the result will be ordered
  • maxResult, in this = 1




Code Block
System.out.println("4.(listMarketCataloque) Get next horse racing market in the UK...\n");
            TimeRange time = new TimeRange();
            time.setFrom(new Date());

            Set<String> countries = new HashSet<String>();

            Set<String> typesCode = new HashSet<String>();

            marketFilter = new MarketFilter();

            Set<MarketProjection> marketProjection = new HashSet<MarketProjection>();

            String maxResult = "1";

            List<MarketCatalogue> marketCatalogueresultmarketCatalogueResult = operationsjsonOperations.listMarketCatalogue(marketFilter, marketProjection, MarketSort.FIRST_TO_START, maxResult,
                    applicationKey, sessionToken);

Get list of runners in the market


To get the list of runners we call the method listMarketBook passing:

  • marketIds: the market id that we got in the previous call
  • priceProjection: the projection of price data you want to receive in the response
  • we don't need orderProjection, matchProjectionand currencyCode that are declared null




Code Block
System.out.println("5. Print static marketId, name and runners....\n");
             * ListMarketBook: get list of runners in the market, parameters:
             * marketId:  the market we want to list runners
            System.out.println("6.(listMarketBook) Get volatile info for Market including best 3 exchange prices available...\n");
            String marketIdChosen = marketCatalogueResult.get(0).getMarketId();

            PriceProjection priceProjection = new PriceProjection();
            Set<PriceData> priceData = new HashSet<PriceData>();

            //In this case we don't need these objects so they are declared null
            OrderProjection orderProjection = null;
            MatchProjection matchProjection = null;
            String currencyCode = null;

            List<String> marketIds = new ArrayList<String>();

            List<MarketBook> marketBookReturn = operationsjsonOperations.listMarketBook(marketIds, priceProjection,
                                           orderProjection, matchProjection, currencyCode, applicationKey, sessionToken);

Place a bet


With all the data needed we can try to place a bet. Based on previous request we provide:

  • marketId: the market id we have found in the previous request
  • instructions: the instructions to place a new order:





  • customerRef: 1 - unique reference for a transaction specified by user, must be different for each request
Code Block
Runner runner;
long selectionId = 0;
            if ( marketBookReturn.size() != 0 ) {
                Runner    runner = marketBookReturn.get(0).getRunners().get(0);
                    selectionId = runner.getSelectionId();
                    System.out.println("Found7. Place a runner with selection id: " + runner.getSelectionId());

      bet below minimum stake to prevent the bet actually " +
                        "being placed for marketId: "+marketIdChosen+" with selectionId: "+selectionId+"...\n\n");
                List<PlaceInstruction> instructions = new ArrayList<PlaceInstruction>();
                    PlaceInstruction instruction = new PlaceInstruction();

                    LimitOrder limitOrder = new LimitOrder();
                    //API-NG will return an error with the default size=0.01. This is an expected behaviour.
                    //YuoYou can adjust the size and price value in the "" file


                    String customerRef = "1";

     System.out.println("Trying to place a bet...");
                     PlaceExecutionReport placeBetResult = operationsjsonOperations.placeOrders(marketIdChosen, instructions, customerRef, applicationKey, sessionToken);

Next, for the placeOrders call, we need to verify the result. This is done using placeBetResult.getStatus() call.

Code Block

                // Handling the operation result
                if (placeBetResult.getStatus() == ExecutionReportStatus.SUCCESS) {
                       System.out.println("Your bet has been placed!!");
                } else if (placeBetResult.getStatus() == ExecutionReportStatus.FAILURE) {
                       System.out.println("Your bet has NOT been placed :*( ");
                       System.out.println("The error is: " + placeBetResult.getErrorCode() + ": " + placeBetResult.getErrorCode().getMessage());
                    System.out.println("Sorry, more luck next time\n\n");
            } else {
                System.out.println("MoreSorry, luckno next timerunners found\n\n");