DEV Community

Max Kleiner
Max Kleiner

Posted on

World News API endpoint2

This function fetches news from a World News API endpoint, parses the JSON response, fills UI fields with article data, and downloads the first article image into an image control. It also returns a text summary of the articles it found, a sentiment analysis or an error message if the HTTP request fails. newsapi
Further you can translate the text with another API.

What it does

  • Builds an HTTP GET request from AURL, searchtext, language, and anumb.
  • Sends the request with JSON headers and an API key.
  • Reads the response as UTF-8 text.
  • Parses the JSON and expects a news array in the response.
  • Loops through each news item and extracts fields like title, text, summary, image, url, sentiment, and source_country.

{$I .\NINJAAPIKEY2.INC}  //stored API-Key

function World_News_API55(AURL, searchtext, language: string; anumb: byte):string;
var httpq: THttpRequestC; //THttpConnectionWinInet;
    jo: TJSON; jarr:TJsonArray2;jobj: TJSonObject2; urlback: string;
    Bmp: TBitmap;
  begin
    mapStream:= TMemoryStream.create;
    Bmp:= TBitmap.Create;
    httpq:= THttpRequestC.create(self); 
    httpq.headers.add('Accept:application/json; charset=utf-8');
    httpq.headers.add('x-api-key:'+WORLDNEWS_APIKEY);
    //httpq.SecurityOptions:= [soSsl3,soPct,soIgnoreCertCNInvalid];
    try
       writ('requrl: '+wideFormat(AURL,[searchtext,language,anumb]));
       httpq.Get(wideFormat(AURL,[searchtext,language,anumb]));
       writ('http get status '+itoa(httpq.response.statuscode2));
       urlback:= httpq.response.ContentAsUTF8String;
       writ('ctype transback: '+(httpq.response.Contenttype));
       jo:= TJSON.Create();
       //StringReplace( backstr, '\n\n', CR+LF,[rfReplaceAll]); 
       writ(StringReplace(formatjson(urlback),'\n', CRLF,[rfReplaceAll]))
       jo.parse((urlback)); 
       jobj:= jo.JsonObject;
       cbb1.clear;
       cbb1.Text:= 'Select News Topic'
       if httpq.response.statuscode2=200 Then begin
          //result:=jobj[0].decode(urlback)
          //result:=jobj['news'].decode(urlback);
          jarr:=jobj['news'].asarray;
          //jarr.decode(jarr.stringify)
          for it:= 0 to jarr.count-1 do begin
            jobj:= jarr.items[it].asobject;
            result:= result+CRLF+itoa(it)+' '+jobj['title'].decode(jobj['title'].stringify);
            result:= result+' sent: '+jobj['sentiment'].stringify;
            result:= result+' src: '+jobj['source_country'].stringify;
            cbb1.items.add(itoa(it)+' '+htmldecode(jobj['title'].decode(jobj['title'].stringify)));
            nsrec[it].ftitle:=  jobj['title'].decode(jobj['title'].stringify);
            nsrec[it].ftext:=  StringReplace(jobj['text'].decode(jobj['text'].stringify),
                                          '.', '.'+CRLF,[rfReplaceAll]);
            nsrec[it].fsummary:= jobj['summary'].decode(jobj['summary'].stringify);
            nsrec[it].fimage:= StrTrimQuotes(jobj['image'].decode(jobj['image'].stringify));
            nsrec[it].furl:= StrTrimQuotes(jobj['url'].decode(jobj['url'].stringify)); 
            nsrec[it].fsentiment:= jobj['sentiment'].stringify;
          end; 
           //StringReplace(formatjson(urlback),'\n', CRLF,[rfReplaceAll]))
          tex1.text:= StringReplace(jobj['text'].decode(jobj['text'].stringify),
                                              '.', '.'+CRLF,[rfReplaceAll]);
          //)writ('response headers '+httpq.response.headers.tostring);    
          writ('response headers quota used:'+httpq.response.headers.getfirst('X-API-Quota-Used')); 
          writ('response headers quota left:'+httpq.response.headers.getfirst('X-API-Quota-Left'));
          newsrecord.fimage:=  jobj['image'].decode(jobj['image'].stringify);
          newsrecord.furl:=  jobj['url'].decode(jobj['url'].stringify);
          writ('debug '+StrTrimQuotes(newsrecord.fimage));
          //Http_GetStream(newsrecord.fimage, mapstream);
          //mapStream.Position:= 0;
          Wininet_HttpGet(StrTrimQuotes(newsrecord.fimage), mapstream);
          writ('debug size: '+itoa(mapstream.size))
          DownloadJPGToBitmap(StrTrimQuotes(newsrecord.fimage), img11.Picture.bitmap);
          //img11.Picture.bitmap.LoadFromStream(mapstream); 
       end else result:='REST API Failed:'+
                itoa(Httpq.response.statuscode2)+httpq.response.headers.tostring; 
    except
       println('EWI_HTTPS: '+ExceptiontoString(exceptiontype,exceptionparam));
    finally
       httpq.free;
       httpq:= Nil;
       jo.free; 
       mapstream.free;   
       bmp.free;   
    end;           
  end;
Enter fullscreen mode Exit fullscreen mode
  • Populates:
    • cbb1 with article titles,
    • newsrecarray[] with per-article data,
    • tex1 with the last article text,
    • newsrecord with the last article’s image and URL.
  • Downloads the image from the last parsed article into img11.Picture.Bitmap.

Return value

If the request succeeds, the function returns a concatenated string containing each article’s index, title, sentiment, and source country. If the HTTP status is not 200, it returns an error string with the status code and response headers. newsapi
The API Get template with string concatenation and the main call example:

TBASE_WORLDNEWSAPI_URL10 = 'https://api.worldnewsapi.com/search-news?text=%s&language=%s&number=%d&earliest-publish-date=2026-06-01';

maxform1.setconsole;
SetBCForm();     
Println(World_News_API55(TBASE_WORLDNEWSAPI_URL10, 'Technic', 'en', 7));    
Enter fullscreen mode Exit fullscreen mode

Important side effects

  • It clears and repopulates the combo box.
  • It changes text in the UI.
  • It stores article data into global or form-level variables.
  • It performs network I/O and image download as part of the same routine.

Code quirks

  • Bmp is created but never used.
  • jo, mapStream, and httpq are freed in finally, but jo may be unsafe if parsing fails before assignment.
  • The function uses the last item in the loop to set tex1, newsrecord, and the downloaded image.
  • It assumes the JSON has a top-level news array; if the API format differs, it will fail or misbehave.

The THttpRequestC dependency is significant because it's the HTTP client component that makes the entire function work: it performs the actual network request to the World News API and returns the response the function parses.

Key significance

Aspect Why it matters
Network I/O Without THttpRequestC, the function cannot make HTTP GET requests to fetch news data github
Custom Delphi component It's a third‑party wrapper for WinInet (indicated by the comment //THttpConnectionWinInet), not a standard Delphi RTL class like THTTPClient or TNetHTTPRequest github
Response data access It provides response.statuscode2, response.ContentAsUTF8String, and response.headers—all critical for checking success, reading JSON, and accessing quota headers github
Header management It lets you add custom headers (Accept, x-api-key) required by the API github
Compilation dependency Your project must include the unit that defines THttpRequestC in the uses clause; otherwise the code won't compile

Practical implications

  • Portability: Since it's a custom wrapper for WinInet, the code is tied to Windows platforms (WinInet is Windows-only) github
  • Availability: You need to have the HttpComponent library (or equivalent) installed; it's not part of standard Delphi/RAD Studio github In maXbox5 the component is included as prebuilt coreclass
  • Alternatives: Standard Delphi HTTP classes (THTTPClient, TNetHTTPClient, IdHTTP) could replace it but would require refactoring the code blog.csdn

In short, THttpRequestC is the core HTTP transport layer—without it, the function has no way to communicate with the API.
Script is available at:
1481_World_News_API1_54form.txt

Top comments (1)

Collapse
 
max_kleiner_9d12e786b3ecc profile image
Max Kleiner

Sentiment analysis (also known as opinion mining) is the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information.