{
"$type": "site.standard.document",
"canonicalUrl": "https://johnnyreilly.com/posts/generate-typescript-and-csharp-clients-with-nswag",
"description": "NSwag simplifies APIs by auto-generating OpenAPI specs and clients. Learn to create TypeScript clients from NSwag using a .NET console app.",
"path": "/posts/generate-typescript-and-csharp-clients-with-nswag",
"publishedAt": "2021-03-06T00:00:00.000Z",
"site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
"tags": [
"swagger",
"c#",
"azure",
"typescript"
],
"textContent": "Generating clients for APIs is a tremendous way to reduce the amount of work you have to do when you're building a project. Why handwrite that code when it can be auto-generated for you quickly and accurately by a tool like NSwag? To quote the docs:\n\n\n\n> The NSwag project provides tools to generate OpenAPI specifications from existing ASP.NET Web API controllers and client code from these OpenAPI specifications. The project combines the functionality of Swashbuckle (OpenAPI/Swagger generation) and AutoRest (client generation) in one toolchain.\n\nThere's some great posts out there that show you how to generate the clients with NSwag using an nswag.json file directly from a .NET project.\n\nHowever, what if you want to use NSwag purely for its client generation capabilities? You may have an API written with another language / platform that exposes a Swagger endpoint, that you simply wish to create a client for. How do you do that? Also, if you want to do some special customisation of the clients you're generating, you may find yourself struggling to configure that in nswag.json. In that case, it's possible to hook into NSwag directly to do this with a simple .NET console app.\n\nThis post will:\n\n- Create a .NET API which exposes a Swagger endpoint. (Alternatively, you could use any other Swagger endpoint; for example an Express API.)\n- Create a .NET console app which can create both TypeScript and CSharp clients from a Swagger endpoint.\n- Create a script which, when run, creates a TypeScript client.\n- Consume the API using the generated client in a simple TypeScript application.\n\nYou will need both Node.js and the .NET SDK installed.\n\nCreate an API\n\nWe'll now create an API which exposes a Swagger / Open API endpoint. Whilst we're doing that we'll create a TypeScript React app which we'll use later on. We'll drop to the command line and enter the following commands which use the .NET SDK, node and the create-react-app package:\n\nWe now have a .NET API with a dependency on NSwag. We'll start to use it by replacing the Startup.cs that's been generated with the following:\n\nThe significant changes in the above Startup.cs are:\n\n1. Exposing a Swagger endpoint with UseOpenApi and UseSwaggerUi3. NSwag will automagically create Swagger endpoints in your application for all your controllers. The .NET template ships with a WeatherForecastController.\n2. Allowing Cross-Origin Requests (CORS) which is useful during development (and will facilitate a demo later).\n\nBack in the root of our project we're going to initialise an npm project. We're going to use this to put in place a number of handy npm scripts that will make our project easier to work with. So we'll npm init and accept all the defaults.\n\nNow we're going add some dependencies which our scripts will use: npm install cpx cross-env npm-run-all start-server-and-test\n\nWe'll also add ourselves some scripts to our package.json:\n\nLet's walk through what the above scripts provide us with:\n\n- Running npm install in the root of our project will not only install dependencies for our root package.json, thanks to our postinstall, install:client-app and install:server-app scripts it will install the React app and .NET app dependencies as well.\n- Running npm run build will build our client and server apps.\n- Running npm run start will start both our React app and our .NET app. Our React app will be started at http://localhost:3000. Our .NET app will be started at http://localhost:5000 (some environment variables are passed to it with cross-env ).\n\nOnce npm run start has been run, you will find a Swagger endpoint at http://localhost:5000/swagger:\n\nThe client generator project\n\nNow we've scaffolded our Swagger-ed API, we want to put together the console app that will generate our typed clients.\n\nWe now have a console app with dependencies on the code generation portions of NSwag. Now let's change up Program.cs to make use of this:\n\nWe've created ourselves a simple .NET console application that creates TypeScript and CSharp clients for a given Swagger URL. It expects three arguments:\n\n- url \\- the url of the swagger.json file to generate a client for.\n- generatePath \\- the path where the generated client file should be placed, relative to this project.\n- language \\- the language of the client to generate; valid values are \"TypeScript\" and \"CSharp\".\n\nTo create a TypeScript client with it then we'd use the following command:\n\nHowever, for this to run successfully, we'll first have to ensure the API is running. It would be great if we had a single command we could run that would:\n\n- bring up the API\n- generate a client\n- bring down the API\n\nLet's make that.\n\nBuilding a \"make a client\" script\n\nIn the root of the project we're going to add the following scripts:\n\nLet's walk through what's happening here. Running npm run generate-client:server-app will:\n\n- Use the start-server-and-test package to spin up our server-app by running the generate-client:server-app:serve script.\n- start-server-and-test waits for the Swagger endpoint to start responding to requests. When it does start responding, start-server-and-test runs the generate-client:server-app:generate script which runs our APIClientGenerator console app and provides it with the URL where our swagger can be found, the path of the file to generate and the language of \"TypeScript\"\n\nIf you were wanting to generate a Cclient (say if you were writing a Blazor app) then you could change the generate-client:server-app:generate script as follows:\n\nConsume our generated API client\n\nLet's run the npm run generate-client:server-app command. It creates a clients.ts file which nestles nicely inside our client-app. We're going to exercise that in a moment. First of all, let's enable proxying from our client-app to our server-app following the instructions in the Create React App docs and adding the following to our client-app/package.json:\n\nNow let's start our apps with npm run start. We'll then replace the contents of App.tsx with:\n\nInside the React.useEffect above you can see we create a new instance of the auto-generated WeatherForecastClient. We then call weatherClient.get() which sends the GET request to the server to acquire the data and provides it in a strongly typed fashion (get() returns an array of WeatherForecast). This is then displayed on the page like so:\n\nAs you an see we're loading data from the server using our auto-generated client. We're reducing the amount of code we have to write _and_ we're reducing the likelihood of errors.\n\nThis post was originally posted on LogRocket.\n\n<head>\n <link rel=\"canonical\" href=\"https://blog.logrocket.com/generate-typescript-csharp-clients-nswag-api/\" />\n</head>",
"title": "NSwag: TypeScript and CSharp client generation based on an API"
}