Consumiendo Web API con Flurl

Es muy común que a la hora de crear aplicaciones móviles nos llegue la idea de poder conectarnos a alguna data proveniente de alguna base de datos u otra fuente especifica, este tipo de interacciones se hacen por medio de algún servicio web, para saber como podemos consumir un servicio web, en este tutorial vamos a utilizar Flurl.

Flurl es un moderno, asíncrono y portable constructor de URL’s y una librería de cliente http para .Net.

Consumir aplicaciones con Flurl es muy sencillo, vamos a ir a nuestro proyecto (yo estoy utilizando un proyecto creado con la extensión de Prism),  primero vamos a descargar los siguientes paquetes y los instalaremos solamente en nuestro proyecto compartido.

Antes de comenzar profundamente con el proyecto, primero vamos a utilizar la siguiente URL para consumir

https://jsonplaceholder.typicode.com/posts

Si abrimos esta URL desde nuestro navegador, la misma nos devolverá una lista en formato Json con las siguientes propiedades.

{
   "userId": 1,
   "id": 1,
   "title": "sunt aut facere repellat provident occaecati excepturi optio 
            reprehenderit",
   "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et 
            cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est 
            autem sunt rem eveniet architecto"
}

Copiamos el primer bloque o bien todo el código que nos devuelva en el navegador e iremos a la siguiente pagina web

https://json2csharp.com/

Vamos a pegar todo lo que copiamos y clickeamos Convert, esto nos devolverá una clase C# en la que solo reemplazaremos el nombre de la clase Root por Post y nos quedara algo así.

public class Post    {
        public int userId { get; set; } 
        public int id { get; set; } 
        public string title { get; set; } 
        public string body { get; set; } 
}

Copiamos el código de esa clase, vamos a nuestro proyecto, crearemos una carpeta y la nombraremos Models y dentro de esa carpeta creamos una clase de nombre Post.cs y reemplazamos el código por el que tenemos anteriormente.

Habiendo hecho esto vamos a ir dentro de la carpeta ViewModels y abriremos el archivo MainPageViewModel.cs y agregaremos el siguiente código.

public ObservableCollection<Post> PostList { get; set; } = new ObservableCollection<Post>();
public ICommand LoadData { get; set; }

public MainPageViewModel(INavigationService navigationService)
: base(navigationService)
{
    Title = "Main Page";
    LoadData = new DelegateCommand(async()=>await LoadDataAPI());
    LoadData.Execute(null);

 }

 public async Task LoadDataAPI() { 
            
 }

Aquí ya tenemos la estructura para empezar a trabajar con Flurl, vamos a ir dentro del método LoadDataAPI, es bien sencillo el uso de esta librería, para empezar simplemente debemos definir una variable para capturar los datos y empezar a construir nuestra URL.

Simplemente digitamos nuestra URL base luego del “Await” y al dar punto al final del string, este nos permitirá ver los métodos con los que Flurl nos permite construir nuestro api.

Seleccionaremos AppendPatchSegment y le enviaremos el método “Posts” y para consumir el servicio, volvemos a dar punto mas y buscamos el método GetJasonAsync.

Aquí vale aclarar, que bien podemos solamente indicarle que nos traiga la data del Json sin definirle ningún tipo de objeto, pero para los fines, necesitamos serializar la data en un objeto con las mismas propiedades del API, como en esta caso estamos recibiendo una colección (lista) de datos, vamos a serializarlos en una lista de tipo Post que es el nombre de la clase modelo que creamos anteriormente.

Al final solo debemos iterar la data ya agregarla a nuestro objeto.

Ahora en nuestro Xaml vamos a tener la siguiente estructura con un collectionview para desplegar la data.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FlurlPost.Views.MainPage"
             Title="{Binding Title}">

    <ContentPage.Content>
        <StackLayout>
            <CollectionView ItemsSource="{Binding PostList}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <Frame Margin="10">
                                <Grid RowDefinitions="Auto,Auto" ColumnDefinitions="*">
                                    <Label Text="{Binding title}" Grid.Column="0" Grid.Row="0" TextColor="Black"/>
                                    <Label Text="{Binding body}" Grid.Column="0" Grid.Row="2"/>
                                </Grid>
                            </Frame>
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
    </ContentPage.Content>

</ContentPage>

Y ejecutaremos nuestra aplicacion y tendremos el siguiente efecto

Gracias por visualizar este post, no olvides dejar un lindo comentario si te gusto.

760 thoughts to “Consumiendo Web API con Flurl”

  1. Hi! I just would like to offer you a big thumbs
    up for the excellent information you have got right here on this post.
    I’ll be coming back to your website for more soon.

  2. Wow, incredible blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your website is wonderful, let alone the
    content!

  3. Выведение Общий клиренс силденафила составляет 41 л/ч, а конечный T1/2 — 3–5 ч. После приема внутрь, также как после в/в введения, силденафил выводится в виде метаболитов, в основном кишечником (около 80% пероральной дозы) и в меньшей степени — почками (около 13% пероральной дозы). Северная Звезда, ЗАО Отмечено снижение клиренса силденафила при одновременном применении ингибиторов изофермента цитохрома СYР3А4 (кетоконазол, эритромицин, циметидин). Циметидин (800 мг), неспецифический ингибитор изофермента цитохрома СYР3А4, при совместном приеме с силденафилом (50 мг) вызывает повышение концентрации силденафила в плазме на 56%. http://gou.nacputte.be/community/profile/pobbrenna276306/ Вообще, пользоваться попперсами следует тогда, когда очень хочется по-настоящему расслабиться и получить максимальное удовольствие от взаимных ласк со своим партнером по время полового акта. Попперсы по своей сути являются соединениями летучей жидкости, которые произведены из нитратов.  Классический попперс AMSTERDAM special 15ml во время отдыха в клу… Выше представлена общая информация о том, как происходит действие попперсов и сколько оно длится. Но сила и продолжительность эффекта могут отличаться в зависимости от пола и особенностей организма, и определить какая марка подойдет именно Вам, можно только на основании собственного опыта применения.

  4. Magnificent goods from you, man. I have bear in mind your stuff prior to and you are
    just extremely great. I actually like what you have
    bought here, really like what you’re stating and the way in which
    in which you are saying it. You make it entertaining and you continue to care for to stay it smart.

    I can’t wait to learn much more from you. That is actually
    a wonderful web site. https://www.herpessymptomsinmen.org/where-to-buy-hydroxychloroquine/

  5. I would like to thank you for the efforts
    you’ve put in writing this website. I’m hoping to see the same
    high-grade content from you in the future as well.
    In fact, your creative writing abilities has inspired me to get my
    own blog now 😉

  6. Superb blog! Do you have any helpful hints for aspiring
    writers? I’m planning to start my own site soon but I’m a little lost on everything.
    Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed ..

    Any tips? Many thanks!

  7. It’s really a nice and useful piece of information. I’m satisfied that you simply
    shared this useful info with us. Please stay
    us up to date like this. Thank you for sharing.

  8. I do believe all the concepts you’ve presented on your post.
    They are very convincing and can definitely work. Nonetheless,
    the posts are too brief for starters. May you please
    lengthen them a little from subsequent time? Thanks for the
    post.

  9. What’s Going down i am new to this, I stumbled upon this I have
    found It absolutely helpful and it has helped me out loads.

    I am hoping to give a contribution & help other customers like its aided me.
    Great job.

  10. Hello my friend! I want to say that this post is awesome, great written and come
    with approximately all vital infos. I would like to look extra posts like this .

  11. Ota paikkasi Boom Casinon Immersive Roulette -poydassa ja valitse haluamasi pelimerkin arvo. Pida mielessa, etta Immersive Roulettemme on tavallinen eurooppalainen versio pelista, jossa on vain yksi nolla. Klikkaa yksinkertaisesti mita tahansa yksittaista numeroa 0 ja 36 valilta, valitse useita numeroita tai valitse vaikka punainen tai musta asettaaksesi panostuksesi. Kun panostusaika on ummessa, krupieeri laittaa kuulan liikkeelle. Kun kuula pysahtyy johonkin kohtaan pyoralle, voittajille maksetaan voitot ja havinneet panostukset poistetaan poydalta. https://www.threefoldlivingllc.com/community/profile/milagrodoris62/ 1xBet Kotikokista loydat ohjeet siihen, miten huippuhyva burgeri! valmistetaan. Reseptia katsottu 17937 kertaa. Katso tama ja sadat muut reseptit sivuiltamme Find and follow posts tagged gluteeniton on Tumblr. PIPARIT (vhh, sokeriton, gluteeniton). Alkuperainen resepti taalta (wholesomeyum.com, luettu 21.12.2017) Katso muita ideoita: Gluteeniton,Gluteeniton leivonta ja Gluteenittomat reseptit. Gluten Free Coffee Cake Muffins. Gluteenittomat Reseptit, Jalkiruokareseptit, Gluteeniton, Reseptit, Terveelliset Reseptit..

  12. You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand.
    It seems too complicated and extremely broad for me. I am looking forward for your next post, I’ll try to get the hang
    of it!

  13. Just wish to say your article is as astonishing.
    The clearness for your submit is just spectacular and i can suppose
    you are a professional on this subject. Well along with your permission allow me to grasp your
    feed to stay updated with impending post.
    Thank you 1,000,000 and please carry on the gratifying work.

  14. Appreciating the dedication you put into your website and detailed information you provide.
    It’s great to come across a blog every once in a while
    that isn’t the same old rehashed information. Wonderful read!

    I’ve saved your site and I’m including your RSS feeds to my Google account.

  15. Pingback: priligy poisoning
  16. Nice post. I be taught something more difficult on totally different blogs everyday. It will always be stimulating to learn content material from different writers and practice a bit one thing from their store. I’d prefer to use some with the content on my weblog whether or not you don’t mind. Natually I’ll give you a hyperlink in your net blog. Thanks for sharing.

  17. Usually I do not learn article on blogs, but I would like to say that this
    write-up very pressured me to try and do it! Your writing style has
    been amazed me. Thank you, very nice post.

  18. Hey there! I know this is kinda off topic however , I’d figured I’d ask.

    Would you be interested in trading links or maybe guest writing a blog post or vice-versa?
    My blog discusses a lot of the same topics as yours and I think we could greatly benefit from each other.
    If you might be interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Superb blog by the way!

  19. A person necessarily lend a hand to make seriously articles I’d state.
    This is the very first time I frequented your website page and up to now?
    I surprised with the analysis you made to make this actual put up extraordinary.
    Great activity!

  20. Animal Crossing: New Horizons, the latest title of the Animal Crossing series, is one of the biggest sellers in Nintendo Switch games released in 2020. A player has his/her own island to develop as a human character, where animal characters live together. The island can be shared with up to 4 players totally, and 8 players can play the online game in the same island simultaneously. The season changes from spring to winter as the real world season does in the social simulation video. https://alumniassociation.ir/community/profile/kareemdecicco75/ Actualidad iPhone is one of the portals with the longest travel in Spanish about Apple news, backed by more than 10 years offering the latest news on Apple and devices such as iPhone, iMac or iPad. You can send your suggestions using the form contact of editorial team. So we started up a side project based around the idea of creating a product that somehow compared Google searches, and The Higher Lower Game – a web game and iOS / Android app that asks players to guess which of two Google search terms is most popular – grew from there.

  21. You made some decent points there. I checked on the net to learn more about the issue and found most people will go along with your views on this website.

  22. Great goods from you, man. I have consider your stuff prior to and
    you’re simply too great. I actually like what you have received
    right here, really like what you’re stating and the best way by which you say it.

    You’re making it entertaining and you continue to take
    care of to keep it sensible. I can not wait to read far more from you.
    That is really a wonderful website.

  23. An outstanding share! I’ve just forwarded this onto a
    coworker who was doing a little homework on this. And he in fact ordered me breakfast because I
    discovered it for him… lol. So allow me to reword this….
    Thank YOU for the meal!! But yeah, thanks for
    spending time to discuss this topic here on your web page.