DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

1

Facilitando Chamadas HTTP com RestSharp

O RestSharp é uma biblioteca popular para facilitar chamadas HTTP em .NET. Ele oferece uma API simples para realizar requisições RESTful, incluindo suporte para GET, POST, PUT, DELETE e outros métodos HTTP. A principal vantagem do RestSharp é sua capacidade de lidar facilmente com serialização e deserialização de dados JSON e XML, além de permitir a criação de chamadas HTTP com headers e parâmetros personalizados. Neste exemplo, vamos demonstrar como fazer uma requisição GET e deserializar a resposta JSON.

Bibliotecas:

Para usar a biblioteca RestSharp, instale o seguinte pacote NuGet no seu projeto:

Install-Package RestSharp
Enter fullscreen mode Exit fullscreen mode

Código de Exemplo:

using RestSharp;
using System;

namespace RestSharpExemplo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Criando o cliente RestSharp
            var client = new RestClient("https://jsonplaceholder.typicode.com");
            var request = new RestRequest("/posts/1", Method.Get);

            // Executando a requisição
            var response = await client.ExecuteAsync<Post>(request);

            if (response.IsSuccessful)
            {
                var post = response.Data;
                Console.WriteLine($"Título: {post.Title}\nConteúdo: {post.Body}");
            }
            else
            {
                Console.WriteLine($"Erro: {response.StatusCode}");
            }
        }
    }

    // Classe para mapear a resposta
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explicação do Código:

Neste exemplo, utilizamos o RestSharp para fazer uma requisição GET à API jsonplaceholder.typicode.com e obter os dados de um post. O objeto RestClient é usado para definir a URL base, e o RestRequest é configurado para a rota específica. A resposta é automaticamente deserializada em um objeto da classe Post. Se a requisição for bem-sucedida, os dados do post são exibidos no console.

Conclusão:

O RestSharp simplifica muito as chamadas HTTP em .NET, oferecendo uma API fácil de usar para realizar requisições e trabalhar com dados RESTful. Sua capacidade de lidar com a serialização/deserialização de objetos o torna uma ferramenta eficiente para integrar com APIs.

Código fonte: GitHub

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay