Skip to content

[Wikibase] Getting started

Chen edited this page Jan 3, 2020 · 6 revisions

Wikibase is the software that enables MediaWiki to store structured data or access data that is stored in a structured data repository, consisting of two MediaWiki extensions, Wikibase Repository and Wikibase Client. Wikidata uses Wikibase as foundation.

For basic concepts used in Wikibase, see mw:Wikibase/API#Wikibase and Wikidata.

Similar to other Wikimedia projects, the MediaWiki API endpoint for Wikidata is https://www.wikidata.org/w/api.php.

Prerequisites

Library references

Fetch entity information

The following examples assume that you have instantiated a WikiSite instance, e.g.

var client = new WikiClient
{
    ClientUserAgent = "..."
};
var myWikiDataSite = new WikiSite(client, "https://www.wikidata.org/w/api.php");

For more information on preparing a WikiSite instance, see [MediaWiki] Getting started.

Note that similar to WikiPage, you can use RefreshAsync extension methods on IEnumerable<Entity> to fetch for a batch of entities at one time.

static async Task FetchEntityAsync()
{
    var entity = new Entity(myWikiDataSite, "Q513");
    await entity.RefreshAsync(EntityQueryOptions.FetchAllProperties);
    Console.WriteLine(entity.Labels["en"]);
    Console.WriteLine(entity.Descriptions["en"]);
    Console.WriteLine("Claims");
    // Enumerate claims
    foreach (var claim in entity.Claims)
    {
        Console.WriteLine("  {0} = {1}", claim.MainSnak.PropertyId, claim.MainSnak.DataValue);
        // Show qualifiers
        foreach (var qualifierSnak in claim.Qualifiers)
        {
            Console.WriteLine("    Qualifier: {0} = {1}", qualifierSnak.PropertyId, qualifierSnak.DataValue);
        }
        // Show references
        foreach (var reference in claim.References)
        {
            Console.WriteLine("    Reference: {0}", reference.Hash);
            foreach (var snak in reference.Snaks)
            {
                Console.WriteLine("      {0} = {1}", snak.PropertyId, snak.DataValue);
            }
        }
    }
}

Expected output

Mount Everest
Earth's highest mountain, with a peak at 8,848 metres (29,029 feet) above sea level, part of the Himalaya mountain range between Nepal and China once in India
Claims
  P17 = Q837
    Reference: fa278ebfc458360e5aed63d5058cca83c46134f1
      P143 = Q328
  P31 = Q8502
    Reference: fa278ebfc458360e5aed63d5058cca83c46134f1
      P143 = Q328
  P373 = Mount Everest
  P242 = Nepal relief location map.jpg
  P227 = 4040417-1
    Reference: c3ba0a726da807d2aa00570597c7b1a29267e529
      P143 = Q1961887
  P214 = 247168735
    Reference: c3ba0a726da807d2aa00570597c7b1a29267e529
      P143 = Q1961887
  P349 = 00628288
  P625 = 27.988055555556°N 86.925277777778°E
    Reference: 9a24f7c0208b05d6be97077d855671d1dfdbc0dd
      P143 = Q48183
  P30 = Q48
    Reference: 3bf39867b037e8e494a8389ae8a03bad6825a7fc
      P143 = Q191168
  P910 = Q7278710
  P935 = ཇོ་མོ་གླང་མ
    Reference: 3bf39867b037e8e494a8389ae8a03bad6825a7fc
      P143 = Q191168
  P18 = Mount everest.jpg
    Qualifier: P2096 = [en]Mount Everest seen from base camp one.
    Qualifier: P585 = 2007-06-07
    Reference: c0623aeb5e42745314018466233282526f7d8c9c
      P854 = https://www.flickr.com/photos/rupertuk/534748923/
  P138 = Q217119
    Qualifier: P580 = Y1865
    Qualifier: P805 = Q2517025
    Reference: 2fb5f1d401c2603010edadf139a9c20538df8604
      P248 = Q23763219
  P646 = /m/0blbd
    Reference: 2b00cb481cddcac7623114367489b5c194901c4a
      P248 = Q15241312
      P577 = 2013-10-28
  P244 = sh85045978
  P948 = Mount Everest banner 2.jpg
  P1566 = 1283416
    Reference: 64133510dcdf15e7943de41e4835c673fc5d6fe4
      P143 = Q830106
  P793 = Q1194369
    Qualifier: P585 = 1953-05-29
    Qualifier: P710 = Q33817
    Qualifier: P710 = Q80732
    Qualifier: P805 = Q4567715
  P2044 = 8848(http://www.wikidata.org/entity/Q11573)
    Reference: fa278ebfc458360e5aed63d5058cca83c46134f1
      P143 = Q328
  P268 = 15289744k
    Reference: d4bd87b862b12d99d26e86472d44f26858dee639
      P143 = Q8447
  P268 = 11963711d
  P2660 = 8848(http://www.wikidata.org/entity/Q11573)
    Reference: 796948eaf1c20bd9c2250838151b820ef78011d8
      P854 = http://www.peakbagger.com/peak.aspx?pid=10640
  P3109 = 10640
  P1296 = 0025628
  P3221 = destination/mount-everest
  P706 = Q924257
    Reference: fa278ebfc458360e5aed63d5058cca83c46134f1
      P143 = Q328
  P1667 = 7001423
  P2924 = 1952857
  P3309 = 150230
  P3417 = Mount-Everest
  P131 = Q837
    Qualifier: P17 = Q837
    Reference: 9a24f7c0208b05d6be97077d855671d1dfdbc0dd
      P143 = Q48183
  P3513 = 80
  P1465 = Q8366750
  P3018 = Q2211959
  P972 = Q5460604
  P361 = Q5451
  P361 = Q208126
  P361 = Q2
  P361 = Q48
  P2659 = 40008(http://www.wikidata.org/entity/Q11573)
  P2347 = 116445
  P1225 = 10038395

Edit entity

You can make multiple edits to the same entity in one API request. Note that the granularity for claim editing is one whole Claim object.

static async Task EditEntityAsync()
{
    // To create a new entity, use
    // var entity = new Entity(myWikiDataSite, EntityType.Item);
    var entity = new Entity(myWikiDataSite, "Q513");
    await entity.RefreshAsync(EntityQueryOptions.FetchClaims);
    var coordinateClaim = entity.Claims["P625"].First();
    coordinateClaim.MainSnak.DataValue = new WbGlobeCoordinate(45, 12, 0.001, WbUri.Get("http://www.wikidata.org/entity/Q2"));

    // Make a some changes
    var edits = new List<EntityEditEntry>
    {
        // Add or update labels.
        new EntityEditEntry(nameof(Entity.Aliases), new WbMonolingualText("en", "Test alias")),
        new EntityEditEntry(nameof(Entity.Descriptions), new WbMonolingualText("en", "Test description")),
        // Add a cliam
        new EntityEditEntry(nameof(Entity.Claims), new Claim("P2044")
        {
            MainSnak = {DataValue = new WbQuantity(1234, WbUri.Get("http://www.wikidata.org/entity/Q11573"))}
        }),
        // Update a claim
        new EntityEditEntry(nameof(Entity.Claims), coordinateClaim),
        // Remove a claim
        new EntityEditEntry(nameof(Entity.Claims), entity.Claims["P948"].Last(), WbEntityEditEntryState.Removed),
    };
    await entity.EditAsync(edits, "Test editing an entity.", EntityEditOptions.Bot);
}

Flavor with generators

The following example enumerates the entities from Q1 to the end. Note that the pages are sorted in alphabetical order, so the second item might be something like Q10 rather than Q2.

static async Task EnumerateEntitiesAsync()
{
    var generator = new AllPagesGenerator(myWikiDataSite)
    {
        StartTitle = "Q1",
        PaginationSize = 50
    };
    using (var enumerator = generator.EnumItemsAsync().Buffer(50).GetEnumerator())
    {
        while (await enumerator.MoveNext())
        {
            var pageStubs = enumerator.Current;
            var entities = pageStubs.Select(stub => new Entity(myWikiDataSite, stub.Title)).ToArray();
            await entities.RefreshAsync(EntityQueryOptions.FetchLabels);
            foreach (var entity in entities)
            {
                Console.WriteLine("{0} ({1})", entity.Labels["en"], entity.Id);
            }
            Console.WriteLine("Esc to exit, any other key for next page.");
            if (Console.ReadKey().Key == ConsoleKey.Escape)
                break;
        }
    }
}