Skip to content
Sann Lynn Htun edited this page Nov 22, 2024 · 1 revision

Refit

Refit is a REST library for .NET, inspired by Square's Retrofit library. It allows you to define a web API as an interface and automatically create a client that implements the interface, making HTTP API calls simple and intuitive.

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; }
}

Refit Example with JSONPlaceholder

Description

The RefitExample class demonstrates how to use the Refit 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.

API Interface

Refit requires you to define an interface that describes your API endpoints.

using Refit;
using System.Collections.Generic;
using System.Threading.Tasks;

public interface IJsonPlaceholderApi
{
    [Get("/posts")]
    Task<List<BlogModel>> GetPosts();

    [Get("/posts/{id}")]
    Task<BlogModel> GetPost(int id);

    [Post("/posts")]
    Task<BlogModel> CreatePost([Body] BlogModel post);

    [Put("/posts/{id}")]
    Task<BlogModel> UpdatePost(int id, [Body] BlogModel post);

    [Delete("/posts/{id}")]
    Task DeletePost(int id);
}

RefitExample Class

public class RefitExample
{
    private readonly IJsonPlaceholderApi _api;

    public RefitExample()
    {
        _api = RestService.For<IJsonPlaceholderApi>("https://jsonplaceholder.typicode.com");
    }

    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);
    }

    private async Task Read()
    {
        var posts = await _api.GetPosts();
        foreach (var post in posts)
        {
            Console.WriteLine(post.Id);
            Console.WriteLine(post.Title);
            Console.WriteLine(post.Body);
            Console.WriteLine("----------------------------");
        }
    }

    public async Task Edit(int id)
    {
        var post = await _api.GetPost(id);
        Console.WriteLine(post.Id);
        Console.WriteLine(post.Title);
        Console.WriteLine(post.Body);
    }

    public async Task Create(string title, string body, int userId)
    {
        var post = new BlogModel
        {
            Title = title,
            Body = body,
            UserId = userId
        };

        var createdPost = await _api.CreatePost(post);
        Console.WriteLine($"Created Post ID: {createdPost.Id}");
        Console.WriteLine(createdPost.Title);
        Console.WriteLine(createdPost.Body);
    }

    public async Task Update(int id, string title, string body, int userId)
    {
        var post = new BlogModel
        {
            Id = id,
            Title = title,
            Body = body,
            UserId = userId
        };

        var updatedPost = await _api.UpdatePost(id, post);
        Console.WriteLine($"Updated Post ID: {updatedPost.Id}");
        Console.WriteLine(updatedPost.Title);
        Console.WriteLine(updatedPost.Body);
    }

    private async Task Delete(int id)
    {
        await _api.DeletePost(id);
        Console.WriteLine("Deleted successfully.");
    }
}

Explanation

1. API Interface

The interface IJsonPlaceholderApi defines the endpoints of the JSONPlaceholder API. Each method is annotated with Refit attributes to specify the HTTP method and the endpoint URL.

2. RefitExample Constructor

public RefitExample()
{
    _api = RestService.For<IJsonPlaceholderApi>("https://jsonplaceholder.typicode.com");
}

Summary: The constructor initializes the Refit client by creating an instance of IJsonPlaceholderApi, specifying the base URL for the API.

3. 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.

4. Read Method

private async Task Read()
{
    var posts = await _api.GetPosts();
    foreach (var post in posts)
    {
        Console.WriteLine(post.Id);
        Console.WriteLine(post.Title);
        Console.WriteLine(post.Body);
        Console.WriteLine("----------------------------");
    }
}

Summary: This method calls the GetPosts method to retrieve all posts from the JSONPlaceholder API and prints each post's data to the console.

5. Edit Method

public async Task Edit(int id)
{
    var post = await _api.GetPost(id);
    Console.WriteLine(post.Id);
    Console.WriteLine(post.Title);
    Console.WriteLine(post.Body);
}

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

6. Create Method

public async Task Create(string title, string body, int userId)
{
    var post = new BlogModel
    {
        Title = title,
        Body = body,
        UserId = userId
    };

    var createdPost = await _api.CreatePost(post);
    Console.WriteLine($"Created Post ID: {createdPost.Id}");
    Console.WriteLine(createdPost.Title);
    Console.WriteLine(createdPost.Body);
}

Summary: This method calls the CreatePost method to create a new post with the provided title, body, and userId. It prints the created post's details.

7. Update Method

public async Task Update(int id, string title, string body, int userId)
{
    var post = new BlogModel
    {
        Id = id,
        Title = title,
        Body = body,
        UserId = userId
    };

    var updatedPost = await _api.UpdatePost(id, post);
    Console.WriteLine($"Updated Post ID: {updatedPost.Id}");
    Console.WriteLine(updatedPost.Title);
    Console.WriteLine(updatedPost.Body);
}

Summary: This method calls the UpdatePost method to update an existing post based on the provided id, title, body, and userId. It prints the updated post's details.

8. Delete Method

private async Task Delete(int id)
{
    await _api.DeletePost(id);
    Console.WriteLine("Deleted successfully.");
}

Summary: This method calls the DeletePost method to remove a post from the API based on the provided id. It confirms the deletion.

Each method in the RefitExample class demonstrates how to interact with the JSONPlaceholder API using the Refit 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