Skip to content

RestSharp

Sann Lynn Htun edited this page Nov 22, 2024 · 2 revisions

RestSharp

RestSharp is a simple REST and HTTP API client library for .NET, making it easy to consume RESTful APIs.

BlogModel Class

Description

The BlogModel class maps the JSON structure used by the JSONPlaceholder API for blog posts.

public class BlogModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public int UserId { get; set; }
}

RestSharp Example with JSONPlaceholder

Description

The RestSharpExample class demonstrates how to use the RestSharp library in C# to interact with the JSONPlaceholder API. This class includes methods to perform the basic CRUD operations (Create, Read, Update, Delete) against the fake API endpoints.

Run Method

public async Task Run()
{
    await Read();
    await Edit(1);
    await Edit(100);
    await Create("title", "body", 1);
    await Update(1, "updated title", "updated body", 1);
    await Delete(1);
}

Summary: This method serves as an entry point to test various API operations. Uncomment the desired operation to execute it.

Read Method

private async Task Read()
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");
    var request = new RestRequest("posts", Method.Get);
    var response = await client.ExecuteAsync<List<BlogModel>>(request);

    if (response.IsSuccessful)
    {
        var posts = response.Data;
        foreach (var post in posts)
        {
            Console.WriteLine(post.Id);
            Console.WriteLine(post.Title);
            Console.WriteLine(post.Body);
            Console.WriteLine("----------------------------");
        }
    }
    else
    {
        Console.WriteLine(response.Content);
    }
}

Summary: This method sends a GET request to the JSONPlaceholder API to retrieve all posts and prints each post's data to the console using RestSharp.

Edit Method

public async Task Edit(int id)
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");
    var request = new RestRequest($"posts/{id}", Method.Get);
    var response = await client.ExecuteAsync<BlogModel>(request);

    if (response.IsSuccessful)
    {
        var post = response.Data;
        Console.WriteLine(post.Id);
        Console.WriteLine(post.Title);
        Console.WriteLine(post.Body);
    }
    else
    {
        Console.WriteLine(response.Content);
    }
}

Summary: This method sends a GET request to retrieve a specific post based on the provided id and prints the details if found.

Create Method

public async Task Create(string title, string body, int userId)
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");
    var post = new BlogModel
    {
        Title = title,
        Body = body,
        UserId = userId
    };
    var request = new RestRequest("posts", Method.Post);
    request.AddJsonBody(post);
    var response = await client.ExecuteAsync(request);

    if (response.IsSuccessful)
    {
        Console.WriteLine(response.Content);
    }
    else
    {
        Console.WriteLine(response.Content);
    }
}

Summary: This method sends a POST request to create a new post with the provided title, body, and userId. It prints the response from the API.

Update Method

public async Task Update(int id, string title, string body, int userId)
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");
    var post = new BlogModel
    {
        Id = id,
        Title = title,
        Body = body,
        UserId = userId
    };
    var request = new RestRequest($"posts/{id}", Method.Put);
    request.AddJsonBody(post);
    var response = await client.ExecuteAsync(request);

    if (response.IsSuccessful)
    {
        Console.WriteLine(response.Content);
    }
    else
    {
        Console.WriteLine(response.Content);
    }
}

Summary: This method sends a PUT request to update an existing post based on the provided id, title, body, and userId. It prints the response from the API.

Delete Method

private async Task Delete(int id)
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");
    var request = new RestRequest($"posts/{id}", Method.Delete);
    var response = await client.ExecuteAsync(request);

    if (response.IsSuccessful)
    {
        Console.WriteLine("Deleted successfully.");
    }
    else
    {
        Console.WriteLine(response.Content);
    }
}

Summary: This method sends a DELETE request to remove a post from the API based on the provided id. It prints the response from the API.

Each method in the RestSharpExample class demonstrates how to interact with the JSONPlaceholder API using the RestSharp library. The class covers basic CRUD operations and ensures asynchronous operations are handled properly.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally