Code Monkey home page Code Monkey logo

pokeapinet's Introduction

PokeApiNet

A .Net wrapper for the Pokemon API at https://pokeapi.co.

Targets .Net Standard 2.0+.

NuGet Build Status

Use

using PokeApiNet;

...

// instantiate client
PokeApiClient pokeClient = new PokeApiClient();

// get a resource by name
Pokemon hoOh = await pokeClient.GetResourceAsync<Pokemon>("ho-oh");

// ... or by id
Item clawFossil = await pokeClient.GetResourceAsync<Item>(100);

To see all the resources that are available, see the PokeAPI docs site.

Internally, PokeApiClient uses an instance of the HttpClient class. As such, instances of PokeApiClient are meant to be instantiated once and re-used throughout the life of an application.

Navigation URLs

PokeAPI uses navigation urls for many of the resource's properties to keep requests lightweight, but require subsequent requests in order to resolve this data. Example:

Pokemon pikachu = await pokeClient.GetResourceAsync<Pokemon>("pikachu");

pikachu.Species only has a Name and Url property. In order to load this data, an additonal request is needed; this is more of a problem when the property is a list of navigation URLs, such as the pikachu.Moves.Move collection.

GetResourceAsync includes overloads to assist with resolving these navigation properties. Example:

// to resolve a single navigation url property
PokemonSpecies species = await pokeClient.GetResourceAsync(pikachu.Species);

// to resolve a list of them
List<Move> allMoves = await pokeClient.GetResourceAsync(pikachu.Moves.Select(move => move.Move));

Paging

PokeAPI supports the paging of resources, allowing users to get a list of available resources for that API. Depending on the shape of the resource data, two methods for paging are included, along with overloads to allow for the specification of the page count limit and the page offset. Example:

// get a page of data (defaults to a limit of 20)
NamedApiResourceList<Berry> firstBerryPage = await client.GetNamedResourcePageAsync<Berry>();

// to specify a certain page, use the provided overloads
NamedApiResourceList<Berry> lotsMoreBerriesPage = await client.GetNamedResourcePageAsync<Berry>(60, 2);

Because the Berry resource has a Name property, the GetNamedResourcePageAsync() method is used. For resources that do not have a Name property, use the GetApiResourcePageAsync() method. Example:

ApiResourceList<ContestEffect> contestEffectPage = await client.GetApiResourcePageAsync<ContestEffect>();

Regardless of which method is used, the returning object includes a Results collection that can be used to pull the full resource data. Example:

Berry cheri = await client.GetResourceAsync<Berry>(firstBerryPage.Results[0]);

Refer to the PokeAPI documention to see which resources include a Name property.

IAsyncEnumerable Support

Two methods expose support for IAsyncEnumerable to make paging through all pages super simple: GetAllNamedResourcesAsync<T>() and GetAllApiResourcesAsync<T>(). Example:

await foreach (var berryRef in pokeClient.GetAllNamedResourcesAsync<Berry>())
{
    // do something with each berry reference
}

Caching

Every resource and page response is automatically cached in memory, making all subsequent requests for the same resource or page pull cached data. Example:

// this will fetch the data from the API
Pokemon mew = await pokeClient.GetResourceAsync<Pokemon>(151);

// another call to the same resource will fetch from the cache
Pokemon mewCached = await pokeClient.GetResourceAsync<Pokemon>("mew");

To clear the cache of data:

// clear all caches for both resources and pages
pokeClient.ClearCache();

Additional overloads are provided to allow for clearing the individual caches for resources and pages, as well as by type of cache.

Build

dotnet build

Test

The test bank includes unit tests and integration tests. Integration tests will actually ping the PokeApi server for data while the unit tests run off of mocked data.

dotnet test --filter "Category = Unit"
dotnet test --filter "Category = Integration"

pokeapinet's People

Contributors

anu6is avatar dependabot[bot] avatar josago97 avatar jotatoledo avatar jruffs7 avatar jtwotimes avatar konvay avatar ldematte avatar lwebb-dev avatar pandascoder avatar phrasmotica avatar schinwinkwinsky avatar towodile avatar treesgobark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pokeapinet's Issues

Implement resource paging

PokeApi supports resource paging for the shallow fetching of lists of data - the library should support this as well. Need to come up with the api for this. Something like:

PokeApiClient client = new PokeApiClient();
var page = await client.GetPageAsync<T>(int? limit, int? offset);

Feature request: Write cache to disk and load on startup

I'm using this API to write a program where I really only need to fetch certain data once (specifically, all Pokemon, moves, and the moves' information), and was wondering if there would be a way to make it so that you can write the disk to cache and load it back if it exists? I know I could use a database for this but it seems overly complex to do so given that I'd have to write special logic for the foreign keys. I'd be willing to implement this if you could point me to where I should look to do it.

Any client calls results in error

I have pulled down the repo, ran a rebuild and then referenced the built dll into a .net framework 4.8 project.

Added this is as test:

           var client = new HttpClient();
            var pokiclient = new PokeApiClient(client);
            var xx = pokiclient.GetResourceAsync<Pokemon>("ho-oh").Result;

And currently get this error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Microsoft.Extensions.Caching.Memory, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.'

This happens in the resource cache manager here:

        /// <summary>
        /// Constructor
        /// </summary>
        public ResourceCacheManager()
        {
            // TODO allow configuration of experiation policies
            _resourceCaches = ResourceTypes.ToImmutableDictionary(x => x, _ => new ResourceCache());
        }

I have tried other client methods and all result in the same error

Removing an item from a page resource also removes it from the cache

So i have a method that gets all pokemon from pokeapi using a call to GetNamedResourcePageAsync and then loops over the results and removes any results that do not match a given filter. When I call GetNamedResourcePageAsync again, instead of all pokemon being returned, only the pokemon that were left after the previous filter are left.
It seems like removing items from the results list is also removing them from the cache

JsonSerializationException thrown in PokeClient.GetResourceAsync<Pokemon> for some (mostly Hisuian) Pokémon.

Error converting value {null} to type 'System.Int32'. Path 'base_experience', line 1, position 354.

This probably is caused by the fact these Pokémon have a "base_experience" with value null in JSON, which cannot directly be converted to Int32 in C#. Making Pokemon.BaseExperience nullable will fix it.

To recreate:

Pokemon wyrdeer = await pokeClient.GetResourceAsync<Pokemon>("wyrdeer");

or use any other pokemon where "base_experience": null.

PokeClient.GetResourceAsync throws NullReferenceException

I have created a new empty Xamarin Andorid project, then added the PokeApiNet package and tested the sample code. When executing the application, it throws an exception of type System.NullReferenceException: 'Object reference not set to an instance of an object.'

I have downloaded the PokeApiNet source code to see what the problem is and it is in the following code:

private async Task<T> GetAsync<T>(string url, CancellationToken cancellationToken)
{
   using var request = new HttpRequestMessage(HttpMethod.Get, url);
   using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

   response.EnsureSuccessStatusCode();
   
   return DeserializeStream<T>(await response.Content.ReadAsStreamAsync());
}

The request is being sent with the HttpCompletionOption.ResponseHeadersRead option, this means that it will process the content of the message even if it is not ready. The error is fixed by changing the option to HttpCompletionOption.ResponseContentRead.

I'm going to upload a pull request with the solution.

Can't fetch the PokemonSpecies for any Pokemon past #808 (Meltan).

each time i try to fetch anything with a national dex number/id higher than 808, i get the following error:
---> Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type 'System.Int32'. Path 'gender_rate', line 1, position 10236.

is gen8 not supported with this wrapper? or is there something i'm missing?

edit: i checked the website for PokeAPI, i'm gonna guess this is something to do with the missing gen8 data. i'm going to be closing this now. sorry about that

Migration to System.Text.Json

Hello, would it be possible to study the change to using System.Text.Json? I understand that using Newtonsoft is beneficial due to the issue of compatibility with previous versions. However, current (and some years-old obsolete) versions of .Net already were and are compatible with System.Text.Json. There are benchmarks that show the improvement in efficiency of System.Text.Json compared to Newtonsoft.

feat request: Add cache logic to page fetch methods

Currently there are no cache mechanisms for neither PokeApiClient#GetApiResourcePageAsync and PokeApiClient.GetNamedResourcePageAsync. If the same page is fetched multiple times then a cache should be hit.

PokemonForm Object Does Not Contain Types

The way to get the typing when pulling from the API is only through
PokemonForm.Pokemon.Types

This can be a slight issue for any Pokemon with multiple forms, example Arceus and all of it's typing forms.
Using the above method, every single form will have the Normal typing. The PokeApi V2 returns a Types property for the forms url that does contain the correct typing.

This URL is for Arceus Bug: https://pokeapi.co/api/v2/pokemon-form/10041
The JSON provided will have the correct Type of Bug

Following the current wrapper implementation, you will be lead to the base Pokemon URL (https://pokeapi.co/api/v2/pokemon/493) which has the typing of Normal

How a selected Pokemon's typing?

Ok so for my project I want the user to be able to pick a pokemon and have the typing for the pokemon displayed but I am having issues.

image

So in the image this is how I am attempting to get the typing for Clefairy. I know it is wrong but when I tried to write in the same way that Clefairy's species is found I am getting errors.

image

I've been at this for hours and I am just trying to learn for personal practice so if anyone can help and explain how to get the typings for a Pokemon I would greatly appreciate it!

Add package to doc site

Once the package is published to nuget.org, add it to the doc site's list of wrapper libraries.

Big images of DreamWorld and Official Artwork

Hello, everybody

At PokeApi is available new Sprites that are not being get by PokeApiNet. The images are bigger and I'm developing a Dotnet Maui app to study and I miss those images. Can I try a Pull Request to update PokemonSprite class?

Showdown sprites missing

PokeAPI, for some reason, also implements the Pokemon Showdown sprites.

They are missing here

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.