-
Notifications
You must be signed in to change notification settings - Fork 5
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.
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; }
}
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.
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);
}
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.");
}
}
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.
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.
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.
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.
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.
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.
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.
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.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.