Example #1
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="SingleResourceRestInterface{T}"/> class.
 /// </summary>
 /// <param name="interfaceName">
 ///     The name of the interface itself which should get appended to the URL.
 ///     For "/todos/123", this should be "todos".
 /// </param>
 /// <param name="id">
 ///     The ID of the resource being accessed.
 ///     For "/todos/123", this should be "123".
 /// </param>
 /// <param name="restClient">
 ///     The <see cref="RestClient"/> which ultimately manages this interface.
 /// </param>
 /// <param name="baseUrlProvider">
 ///     An <see cref="IUrlProvider"/> which is the logical parent of this interface.
 ///     The URL which is provided by this <see cref="IUrlProvider"/> is used as this
 ///     interface's URL. If <see langword="null"/>, the <paramref name="restClient"/> is
 ///     used instead.
 /// </param>
 internal SingleResourceRestInterface(
     string interfaceName,
     int id,
     JsonPlaceholderClient restClient,
     IUrlProvider?baseUrlProvider = null)
     : base(restClient, baseUrlProvider)
 {
     _interfaceName = interfaceName ?? throw new ArgumentNullException(nameof(interfaceName));
     _id            = id;
 }
 public JsonPlaceholderController(IHttpContextAccessor httpContextAccessor)
 {
     _jsonPlaceholderClient = new JsonPlaceholderClient
                              (
         new HttpClient
     {
         BaseAddress = new Uri(_baseUri)
     },
         httpContextAccessor
                              );
 }
Example #3
0
        public static async Task Main()
        {
            // To dive into the code:
            // Start with the JsonPlaceholderClient.cs file.
            // Then follow the comments in there.

            // Using the API wrapper client:
            // Usually, you just create an instance somewhere and (optionally) pass a configuration.
            var client = new JsonPlaceholderClient();

            // Then you can just use the fluent API to follow the REST API:
            var getAllTodosResponse = await client.Todos().Get().FetchResponseAsync();

            var getAllTodosResource = await getAllTodosResponse.DeserializeResourceAsync();

            // An important thing to know is the difference between Response and Resource.
            //
            // Response means the whole HTTP response data returned from the API, i.e.
            // the status code, the headers, the content, ...
            //
            // Resource means the deserialized .NET POCO that can be parsed from the response's
            // HttpContent.
            // As you can see above, it can be retrieved from an ApiResponse via the
            // DeserializeResourceAsync() method.
            //
            // With the deserialized resource, we, as a user, can now interact with the result
            // returned by the API - without having to worry about anything like status codes!

            if (getAllTodosResource.TryGetValue(out IEnumerable <TodoItem> todos))
            {
                WriteLine($"Fetched {todos.Count()} todos!");

                foreach (var todo in todos)
                {
                    WriteLine($"  - {todo.Title}");
                }
            }
            else
            {
                WriteLine("Failed to load any todos...");
            }
        }
        public async Task Given_AlbumsRequested_When_Retrieved_Then_MergeAlbumsAndPhotos_And_Return()
        {
            // Arrange
            const string albumsResponse = @"
                [
                    {
                        userId: 1,
                        id: 1,
                        title: ""Album 1""
                    },
                    {
                        userId: 1,
                        id: 2,
                        title: ""Album 2""
                    }
                ]";

            const string photosResponse = @"[
                {
                    albumId: 1,
                    id: 1,
                    title: ""Photo 1"",
                    url: ""https://via.placeholder.com/600/92c952"",
                    thumbnailUrl: ""https://via.placeholder.com/150/92c952""
                },
                {
                    albumId: 1,
                    id: 2,
                    title: ""Photo 2"",
                    url: ""https://via.placeholder.com/600/771796"",
                    thumbnailUrl: ""https://via.placeholder.com/150/771796""
                },
                {
                    albumId: 2,
                    id: 3,
                    title: ""Photo 3"",
                    url: ""https://via.placeholder.com/600/771796"",
                    thumbnailUrl: ""https://via.placeholder.com/150/771796""
                }
            ]";


            var client = Substitute.For <IHttpClient>();
            var sut    = new JsonPlaceholderClient(client, new Uri("http://fake-api.com"));

            client.GetStringAsync(Arg.Is <Uri>(uri => uri.AbsoluteUri.EndsWith("albums"))).Returns(albumsResponse);
            client.GetStringAsync(Arg.Is <Uri>(uri => uri.AbsoluteUri.EndsWith("photos"))).Returns(photosResponse);

            // Act
            var result = await sut.GetAlbumsAsync();

            // Assert
            Assert.Collection(result, a =>
            {
                Assert.Equal("Album 1", a.Title);
                Assert.Collection(a.Photos, p =>
                {
                    Assert.Equal("Photo 1", p.Title);
                    Assert.Equal(new Uri("https://via.placeholder.com/600/92c952", UriKind.Absolute), p.Url);
                    Assert.Equal(new Uri("https://via.placeholder.com/150/92c952", UriKind.Absolute), p.ThumbnailUrl);
                }, p =>
                {
                    Assert.Equal("Photo 2", p.Title);
                    Assert.Equal(new Uri("https://via.placeholder.com/600/771796", UriKind.Absolute), p.Url);
                    Assert.Equal(new Uri("https://via.placeholder.com/150/771796", UriKind.Absolute), p.ThumbnailUrl);
                });
            }, a =>
            {
                Assert.Equal("Album 2", a.Title);
                Assert.Collection(a.Photos, p =>
                {
                    Assert.Equal("Photo 3", p.Title);
                    Assert.Equal(new Uri("https://via.placeholder.com/600/771796", UriKind.Absolute), p.Url);
                    Assert.Equal(new Uri("https://via.placeholder.com/150/771796", UriKind.Absolute), p.ThumbnailUrl);
                });
            });
        }
Example #5
0
 internal PostInterface(int id, JsonPlaceholderClient restClient, IUrlProvider?baseUrlProvider = null)
     : base("posts", id, restClient, baseUrlProvider)
 {
 }
Example #6
0
 public UserController(JsonPlaceholderClient jsonPlaceholderClient)
 {
     _jsonPlaceholderClient = jsonPlaceholderClient;
 }
Example #7
0
 internal TodoInterface(int id, JsonPlaceholderClient restClient, IUrlProvider?baseUrlProvider = null)
     : base("todos", id, restClient, baseUrlProvider)
 {
 }
Example #8
0
 internal UserInterface(int id, JsonPlaceholderClient restClient, IUrlProvider? baseUrlProvider = null)
     : base("users", id, restClient, baseUrlProvider) { }
Example #9
0
 public PostsController(JsonPlaceholderClient httpClient, ILogger <PostsController> logger)
 {
     _httpClient = httpClient;
     _logger     = logger;
 }
Example #10
0
 internal AlbumInterface(int id, JsonPlaceholderClient restClient, IUrlProvider?baseUrlProvider = null)
     : base("albums", id, restClient, baseUrlProvider)
 {
 }