user5850934
user5850934

Reputation:

Web-api controller to extract data from Wikipedia api in json format and show the result on web

In my project I am using 3 Wikipedia API in Json formatted to extract the data from it. The first API contain the short-text of the Wikipedia article of places that means the first paragraph of the article. The second API contain the Latitude and longitude of the places. And From the Third API I got the page-image URL information of that places. Now I want to implement my code using Web-API Controller with ASP.Net MVC. My Wikipedia-API for shortext is- https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Berlin&redirects=

Wikipedia Api forLatitide and Longitude is- https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&titles=Berlin

So Far What I have done is create three folders inside the Model named ShortText, Image and Geo accordingly.

Inside the ShortText folder I created four classes contain json object and named these Limits.cs, Pageval.cs, Query.cs and Rootobject.cs

Limits.cs

public class Limits
{
 public int extracts { get; set; }
 }

Pageval.cs

public class Pageval
{
 public int pageid { get; set; }
 public int ns { get; set; }
 public string title { get; set; }
 public string extract { get; set; }
}

Query.cs

 public class Query
 { 
  public Dictionary<string, Pageval> pages { get; set; }
 }

Rootobject.cs

 public class Rootobject
 {
  public string batchcomplete { get; set; }
  public Query query { get; set; }
  public Limits limits { get; set; }
 }

For the Latidute and longitude I created 4 classes inside Geo Folder inside The Model named Coordinate.cs,GeoQuery.cs,GeoRootobject.cs,PageId,

 public class Coordinate
{
    public double lat { get; set; }
    public double lon { get; set; }
    public string primary { get; set; }
    public string globe { get; set; }
}

public class GeoQuery
{
    public Dictionary<string, PageId> pages { get; set; }
}

public class GeoRootobject
{
    public string batchcomplete { get; set; }
    public GeoQuery query { get; set; }
}

public class PageId
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public List<Coordinate> coordinates { get; set; }
}

For the PageImage I created 4 classes inside Image Folder inside The Model named ImgPageval.cs,ImgQuery.cs,ImgRootobject.cs,Thumbnail.cs,

 public class ImgPageval
 {
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public Thumbnail thumbnail { get; set; }
    public string pageimage { get; set; }
 }

 public class ImgQuery
 {
    public Dictionary<string, ImgPageval> pages { get; set; }
 }

  public class ImgRootobject
  {
    public string batchcomplete { get; set; }
    public ImgQuery query { get; set; }
  }
  public class Thumbnail
  {
    public string source { get; set; }
    public int width { get; set; }
    public int height { get; set; }
 }

So Now Inside the Controller I created a Web-API 2 Controller class Which I want to use for writing code to extract data-

Here my code is not working at all.It doesn't what I want to see on the web.I wrote my code in the following way. But I thing this is not the corrext way to get the data

 public class WikiController : ApiController
  {


    // GET: api/Wiki

    public string Get(string Name)
    {

        string result;

        using (WebClient client = new WebClient())
        {

            var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + Name + "&redirects=");

            var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
            var firstKey = responseJson.query.pages.First().Key;
            var extract = responseJson.query.pages[firstKey].extract;

            try
            {
                Regex regex = new Regex(@".(?<=\()[^()]*(?=\)).(.)");
                string.Format("Before:{0}", extract);
                extract = regex.Replace(extract, string.Empty);
                string result1 = String.Format(extract);
                result = Regex.Replace(result1, @"\\n", " ");
            }


            catch (Exception)
            {
                result = "Error";
            }
        }



        return result;
    }

My Routconfig and webapiconfig class is as-

   public class RouteConfig
   {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
     }
   }

WebApiConfig.cs is

   public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

I want to get my Result in the following way in web-

{
 "Name": "Burgtor",
  "Shorttext": "The Burgtor, built 1444 in late Gothic style, was the northern city gate of Hanseatic Lübeck....
 "GeoCoordinates": {
 "Longitude": 10.6912,
 "Latitude": 53.8738
 },
  "Images": [
  "8AB1DF99.jpg or //Image url"
 ]
}

I am trying a lot to find a solution to get this result. But as I am very new handing The MVC Web Api Controller. I am not getting correct way to proceed.Also trying hard to get a way of processing the Url json web api through web api controller. Sorry for such a long description.

Upvotes: 0

Views: 616

Answers (1)

Dennis Rosenbaum
Dennis Rosenbaum

Reputation: 379

Where you have the try catch blocks, you could fill your custom result class and return that.

Something like this:

public class GeoCoordinates 
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class LocationResult
{
    public string Name { get; set; }
    public string Shorttext { get; set; }
    public GeoCoordinates GeoCoordinates { get; set; }
    public List<string> Images { get; set; }    
}

And then in your code fill the LocationResult and return the serialized version of that.

var result = new LocationResult();
result.Shorttext = responseJson.query.pages[firstKey].extract;
result.Name = responseJson.query.pages[firstKey].title;
//etc.

return JsonConvert.SerializeObject(result);

Resulting in:

public string Get(string id)
        {
            using (WebClient client = new WebClient())
            {

            var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + id + "&redirects=");

            var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
            var firstKey = responseJson.query.pages.First().Key;

            var result = new LocationResult();
            result.Shorttext = responseJson.query.pages[firstKey].extract;
            result.Name = responseJson.query.pages[firstKey].title;
            //etc.

            return JsonConvert.SerializeObject(result);
        }
    }

Upvotes: 0

Related Questions