{"id":13629601,"url":"https://github.com/Jalalx/HttpClientCodeGenerator","last_synced_at":"2025-04-17T09:35:02.472Z","repository":{"id":47177504,"uuid":"389226912","full_name":"Jalalx/HttpClientCodeGenerator","owner":"Jalalx","description":"HttpClientGenerator is a tool that uses the Roslyn code generator feature to write boilerplate HttpClient code for you.","archived":false,"fork":false,"pushed_at":"2021-09-09T18:54:52.000Z","size":98,"stargazers_count":46,"open_issues_count":1,"forks_count":2,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-08-01T22:44:00.509Z","etag":null,"topics":["csharp-sourcegenerator","httpclient","roslyn-generator","source-generator"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Jalalx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-07-25T00:32:50.000Z","updated_at":"2024-06-23T11:47:40.000Z","dependencies_parsed_at":"2022-09-04T01:20:53.922Z","dependency_job_id":null,"html_url":"https://github.com/Jalalx/HttpClientCodeGenerator","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jalalx%2FHttpClientCodeGenerator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jalalx%2FHttpClientCodeGenerator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jalalx%2FHttpClientCodeGenerator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jalalx%2FHttpClientCodeGenerator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Jalalx","download_url":"https://codeload.github.com/Jalalx/HttpClientCodeGenerator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223751274,"owners_count":17196602,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp-sourcegenerator","httpclient","roslyn-generator","source-generator"],"created_at":"2024-08-01T22:01:14.616Z","updated_at":"2024-11-08T20:31:21.938Z","avatar_url":"https://github.com/Jalalx.png","language":"C#","readme":"# HttpClientGenerator\n\n![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/jalalx/HttpClientCodeGenerator/Main/main)\n![HttpClientGenerator Nuget (with prereleases)](https://img.shields.io/nuget/vpre/httpclientgenerator)\n\nHttpClientGenerator is a tool that uses [Roslyn source generator feature](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/) to write boilerplate HttpClient code for you.\n\n## The Philosophy\n\u003e You should not write or generate boilerplate code. Your repository should not host or track auto-generated code.\n\nThis leaves you with:\n* A much cleaner codebase\n* No need for calling generator tool everytime HTTP contracts change\n* You do not need to maintain or have a separate tool around out of your repo\n* And no dependency on any 3rd-party code at runtime!\n\n### Installing\n```sh\ndotnet add package HttpClientGenerator\n```\n\n### Usage\n1. Create a console app (net5.0 app)\n2. Install the `HttpClientGenerator` nuget package\n3. Add following code to your project:\n    ```csharp\n    //using area\n    using HttpClientGenerator.Shared;\n    using System.Text.Json.Serialization;\n    // ...\n    namespace ConsoleClientApp\n    {\n        // Make sure to mark the class and method as partial!\n        public partial class ToDoHttpService\n        {\n            [HttpGet(\"todos/{id}\")]\n            public partial Task\u003cToDoItem\u003e GetToDoItemByIdAsync(int id);    \n        }\n\n        public class ToDoItem\n        {\n            [JsonPropertyName(\"id\")]\n            public int Id { get; set; }\n\n            [JsonPropertyName(\"firstName\")]\n            public int? UserId { get; set; }\n\n            [JsonPropertyName(\"title\")]\n            public string Title { get; set; }\n\n            [JsonPropertyName(\"completed\")]\n            public bool IsCompleted { get; set; }\n        }\n    }\n    ```\n    Notice to the `partial` keyword on class and method definition. The library generates the required `GetToDoItemByIdAsync` method for you. All you need to do is to call the method like this:\n    ```csharp\n    static class Program\n    {\n        static async Task Main(string[] args)\n        {\n            // Todo: Use HttpClientFactory to create HttpClient instance. Read more at: \n            // https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests\n            using (var client = new HttpClient())\n            {\n                client.BaseAddress = new Uri(\"https://jsonplaceholder.typicode.com\");\n            \n                // The tool will generate a constructor with HttpClient argument for you\n                var todoService = new ToDoHttpService(client);\n            \n                // Simply call the partial method, the tool has generated the required code for you\n                var item = await todoService.GetToDoItemByIdAsync(1);\n\n                Console.WriteLine($\"Task {item.Title}: completed: {item.IsCompleted}\");\n            }\n\n            Console.Read();\n        }\n    }\n    ```\n\n    Behind the scene, the tool generates following code for you:\n    ```csharp\n    // \u003cauto-generated\u003e\n    //     This code was generated by HttpClientCodeGenerator.\n    // \u003c/auto-generated\u003e\n\n    using System;\n    using System.Net.Http;\n    using System.Threading.Tasks;\n    using System.Collections.Generic;\n    using ConsoleClientApp;\n    using HttpClientGenerator.Shared;\n\n\n    namespace ConsoleClientApp\n    {\n        public partial class ToDoHttpService\n        {\n            protected readonly HttpClient _httpClient;\n        \n            public ToDoHttpService(HttpClient httpClient)\n            {\n                _httpClient = httpClient;\n            }\n        \n            public partial async Task\u003cToDoItem\u003e GetToDoItemByIdAsync(int id)\n            {\n                const string @___httpMethod = \"GET\";\n            \n                var @___path = \"todos/{id}\";\n                var @___routes = new Dictionary\u003cstring, object\u003e();\n                @___routes[\"id\"] = id;\n            \n                var @___queryParams = new Dictionary\u003cstring, object\u003e();\n                // Query String dictionary goes here...\n            \n                var @___headers = new Dictionary\u003cstring, string\u003e();\n                // Header dictionary goes here...\n            \n                return await HttpClientGenerator.Shared.HttpClientHelper.SendAsync\u003cToDoItem\u003e(_httpClient, @___httpMethod, @___path, @___headers, @___routes, @___queryParams);\n            }\n        \n        }\n    }\n\n    ```\n    NOTE: *This code is generated on the fly and is not written on disc so you don't have to worry about adding it to source control or debugging it.*\n\n4. Now you can build and run!\n\n```\n// output\nTask delectus aut autem: completed: False\n```\n\nIt's cool, isn't it?\n\n### Default JSON serializer\nYou can change the default `JsonSerializerOptions` by modifying the singleton reference at `HttpClientHelper.DefaultJsonSerializerOptions`. In the default implementation `JsonSerializerOptions.PropertyNameCaseInsensitive` is set to `true` to cover most use cases.\n\n### About `HttpClient` injection\n\nThe tool automatically adds a constructor with a `HttpClient` parameter in the generated code but you can provide\na `HttpClient` instance manually by using one of the following methods:\n\n#### Introducing a field or property\n\nIf you add a constructor and provide a `HttpClient` field or property, the generator will use that field:\n\n```csharp\npublic partial class ToDoHttpService\n{\n    // The generator will pick up this field (or Property)\n    protected readonly HttpClient _httpClient;\n    \n    // protected HttpClient HttpClient { get; } = new HttpClient();\n        \n    public ToDoHttpService(HttpClient httpClient)\n    {\n        _httpClient = httpClient;\n    }\n    // ... rest of code\n}\n```\n\n#### Introducing a method\n\nIf you have a parameterless method that returns `HttpClient`, the generator will pick it up:\n\n```csharp\npublic partial class ToDoHttpService\n{\n    // The generator will call this method when needs a HttpClient instance\n    private HttpClient MyCustomHttpClientResolver()\n    {\n        var client = new HttpClient();\n        // initialize the client here...\n        return client;\n    }\n    // ... rest of code\n}\n```\n\n### Recommended way:\nWe strongly suggest to use `IHttpClientFactory` to resolve `HttpClient` instances. You can read more about it here: [Use IHttpClientFactory to implement resilient HTTP requests](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests)\n\n### Known Issues\n* You will currently need to restart Visual Studio 2019 to see IntelliSense and get rid of errors with the early tooling experience.\n* During development of this library using Visual Studio, make sure [you have read this issue](https://github.com/dotnet/roslyn/issues/48083).\n* If you are using Visual Studio Code (Omnisharp C# extension) you might see some red lines under the partial method.\nUntil now, there is no full support for this feature on Omnisharp, but dotnet SDK will work without problem.\n\n**Please feel free to open issue for reporting a bug or missing feature.**\n","funding_links":[],"categories":["Source Generators","Do not want to test 112 ( old ISourceGenerator )"],"sub_categories":["Webprogramming","1. [ThisAssembly](https://ignatandrei.github.io/RSCG_Examples/v2/docs/ThisAssembly) , in the [EnhancementProject](https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples#enhancementproject) category"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJalalx%2FHttpClientCodeGenerator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FJalalx%2FHttpClientCodeGenerator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJalalx%2FHttpClientCodeGenerator/lists"}