<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ TypeSpec - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ TypeSpec - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 20 Jul 2026 09:56:39 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/typespec/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use TypeSpec for Documenting and Modeling APIs ]]>
                </title>
                <description>
                    <![CDATA[ If you're curious and passionate about technology like I am, and you’re looking for clarity in your code, you've likely already experienced the limitations of conventional tools for documenting and modeling APIs. Tools such as Swagger, JSON Schema, o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-typespec-for-documenting-and-modeling-apis/</link>
                <guid isPermaLink="false">67f96c998b09f2bdfa144c8b</guid>
                
                    <category>
                        <![CDATA[ TypeSpec ]]>
                    </category>
                
                    <category>
                        <![CDATA[ openai ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Adalbert Pungu ]]>
                </dc:creator>
                <pubDate>Fri, 11 Apr 2025 19:25:13 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744399481891/de5db16a-2eea-46d8-820d-50c1e66d5019.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're curious and passionate about technology like I am, and you’re looking for clarity in your code, you've likely already experienced the limitations of conventional tools for documenting and modeling APIs.</p>
<p>Tools such as Swagger, JSON Schema, or OpenAPI are powerful, but they can be verbose, inflexible, or not conducive to reuse.</p>
<p>Well, I recently discovered TypeSpec. In this guide, I’ll show you how to take advantage of TypeSpec to create modern, maintainable, and well-documented REST APIs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744242129685/403f9a32-8d06-47e2-b551-2ec1de1f6c0a.png" alt="Screenshot of the TypeSpec website. It features a dark background with &quot;Design APIs&quot; in large text and a description about designing data to generate schemas, specifications, code, and more. It includes &quot;Install&quot; and &quot;Playground&quot; buttons at the top." class="image--center mx-auto" width="1730" height="765" loading="lazy"></p>
<p>We'll take a look at:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-typespec">What is TypeSpec?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-typespec">Why use TypeSpec?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-install-and-configure-typespec">How to Install and Configure TypeSpec</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-typespec-basic-syntax">TypeSpec Basic Syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-rest-api-model">How to Create a REST API Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-the-api-in-express-and-aspnet-core">How to Build the API in Express and</a> <a target="_blank" href="http://ASP.NET">ASP.NET</a> <a class="post-section-overview" href="#heading-how-to-build-the-api-in-express-and-aspnet-core">Core</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-structuring-typespec-projects-and-components">Best Practices for Structuring TypeSpec Projects and Components</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Before we dive into using TypeSpec to document and model APIs, here are a few things you'll need to familiarize yourself with and/or have:</p>
<ul>
<li><p><strong>Node.js</strong> (version 18 or higher)</p>
</li>
<li><p><strong>npm</strong> for dependency management</p>
</li>
<li><p><strong>Visual Studio Code</strong> (recommended to take advantage of the official TypeSpec extension). For an optimal experience, to create your project easily, it provides syntax highlighting, validation, autocompletion, navigation, and more.</p>
</li>
<li><p><strong>TypeSpec Extension</strong> in VS Code (You can install the extension via <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=typespec.typespec-vscode">Visual Studio Marketplace</a>)</p>
</li>
<li><p>An understanding of how to use and create APIs</p>
</li>
</ul>
<h2 id="heading-what-is-typespec">What is TypeSpec?</h2>
<p>TypeSpec is an open-source declarative language, developed by Microsoft, designed to describe APIs in an explicit, reusable, scalable, and standards-based way. It’s designed to model REST, gRPC, GraphQL, and other types of APIs, and offers a modern syntax close to TypeScript.</p>
<p>It can automatically generate:</p>
<ul>
<li><p>OpenAPI, JSON Schema, or Protobuf specifications</p>
</li>
<li><p>server and client code</p>
</li>
<li><p>API documentation</p>
</li>
<li><p>and other interface-related artifacts</p>
</li>
</ul>
<p>TypeSpec isn't just a language – it's an API design platform that favors abstraction, encourages code reuse, and integrates with modern tools like Visual Studio Code via a dedicated extension. You can install the extension via the VS Code <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=typespec.typespec-vscode">Visual Studio Marketplace</a>.</p>
<h2 id="heading-why-use-typespec">Why use TypeSpec?</h2>
<p>Before diving into the code, let's take a minute to understand the TypeSpec philosophy. Microsoft uses TypeSpec internally to deliver high-quality API services to millions of customers, across tens of thousands of endpoints, while ensuring code quality, governance, and scalability.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744242196525/a1947dfb-e46d-4083-95c5-218615ab75e6.png" alt="Screenshot with the text on a dark background reads: &quot;Why TypeSpec - API-First for developers. With TypeSpec, remove the handwritten files that slow you down, and generate standards-compliant API schemas in seconds.&quot;" class="image--center mx-auto" width="1823" height="502" loading="lazy"></p>
<p>Unlike generators such as Swagger, Codegen, or Postman, which start from an OpenAPI file to generate code, TypeSpec does the opposite: you first write your API design in a DSL (Domain Specific Language), then generate everything you need.</p>
<p>TypeSpec has been designed to meet the major challenges of large-scale API design and governance:</p>
<ul>
<li><p><strong>Simplification</strong>: clear, concise syntax to focus on business logic.</p>
</li>
<li><p><strong>Reusability</strong>: encapsulates types, request/response models, and directives in modular components.</p>
</li>
<li><p><strong>Productivity</strong>: automatically generates the necessary resources from a single source definition.</p>
</li>
<li><p><strong>Consistency</strong>: maintains compliance with internal standards thanks to shared libraries.</p>
</li>
<li><p><strong>Interoperability</strong>: integrates with the OpenAPI ecosystem and supports multi-format generation.</p>
</li>
<li><p><strong>Scalability</strong>: designed to handle thousands of endpoints like those used by Microsoft Azure.</p>
</li>
</ul>
<p>Let's take a look at how to install and configure the development environment</p>
<h2 id="heading-how-to-install-and-configure-typespec">How to Install and Configure TypeSpec</h2>
<p>Before you can start writing your first API with TypeSpec, you need to set up your development environment. Here's how to install TypeSpec on your machine.</p>
<h4 id="heading-requirements">Requirements:</h4>
<ul>
<li><p><strong>Node.js</strong> (version 18 or higher)</p>
</li>
<li><p><strong>npm</strong> for dependency management</p>
</li>
<li><p><strong>Visual Studio Code</strong> (recommended to take advantage of the official TypeSpec extension). For an optimal experience, it provides syntax highlighting, validation, autocompletion, navigation, and more.</p>
</li>
</ul>
<p>TypeSpec CLI global installation:</p>
<pre><code class="lang-bash">npm install -g @typespec/compiler
</code></pre>
<h3 id="heading-how-to-create-a-typespec-project">How to Create a TypeSpec Project</h3>
<p>The easiest way to create a project is to use Visual Studio Code via the TypeSpec extension you've installed (if you're not comfortable with the command line (CMD)).</p>
<p>Create a folder containing the project and open it with Visual Studio Code. Then click on the <code>View</code> tab, and next on <code>Comment Palette</code> .</p>
<p>In the search bar that appears, enter <code>TypeSpec: Create TypeSpec Project</code>.</p>
<p>Follow the quick selections to select the root folder of the project you've just created. Then choose the Template – for our case this will be <code>Generic REST API</code> – and enter the project name. Leave the emitter <code>OpenAPI 3.1 document</code> (3.1 is the current version at the time of writing) selected by default. This will put us <code>@typespec/http@typespec/openapi3</code>. Finally, wait for the project configuration to finish.</p>
<p>You should have a basic TypeSpec project configuration with a structure that looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744242632713/69485276-b885-450c-870a-56af5e6d8122.png" alt="A screenshot of a file explorer showing a folder named &quot;node_modules&quot; and files: .gitignore, main.tsp, package-lock.json, package.json, and tspconfig.yaml." class="image--center mx-auto" width="748" height="298" loading="lazy"></p>
<ul>
<li><p><strong>node_modules/</strong>: Directory where npm installs project dependencies.</p>
</li>
<li><p><strong>main.tsp</strong>: the entry point for your TypeSpec build. This file generally contains the main definitions of your models, services, and operations.</p>
</li>
<li><p><strong>package.json</strong>: Contains project metadata, including dependencies, scripts, and other project-related information.</p>
</li>
<li><p><strong>tspconfig.yaml</strong>: TypeSpec compiler configuration file, specifying options and parameters for the generation process.</p>
</li>
</ul>
<p>You can also run <code>tsp compile .</code> to compile the project, but it's better to run <code>tsp compile . --watch</code> to automatically compile changes during development each time you save.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744242865089/dea4c75e-80e3-454d-a1ab-af4186423271.png" alt="A command-line interface showing the successful compilation of a project using TypeSpec compiler v1.0.0-rc.0, with output to &quot;tsp-output/schema/&quot;." class="image--center mx-auto" width="895" height="295" loading="lazy"></p>
<p>Once the project has been compiled, you'll see the <code>tsp-output</code> and <code>schema</code> folders generated and a file added <code>openai.yaml</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744242771607/ad948a7c-ea56-44df-861d-7fa04cad1a6d.png" alt="File directory structure with folders &quot;node_modules&quot; and &quot;tsp-output&quot;, containing files like &quot;openapi.yaml&quot;, &quot;.gitignore&quot;, &quot;main.tsp&quot;, &quot;package-lock.json&quot;, &quot;package.json&quot;, and &quot;tsconfig.yaml&quot;." class="image--center mx-auto" width="1064" height="259" loading="lazy"></p>
<ul>
<li><p><strong>tsp-output/</strong>: Directory where the TypeSpec compiler generates files.</p>
</li>
<li><p><strong>openapi.yaml</strong>: OpenAPI specification file generated for your API, detailing API endpoints, templates, and operations. Output may vary depending on the target format specified in the <code>tspconfig.yaml</code> file.</p>
</li>
</ul>
<pre><code class="lang-yaml"><span class="hljs-attr">emit:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">"@typespec/openapi3"</span>
<span class="hljs-attr">options:</span>
  <span class="hljs-string">"@typespec/openapi3"</span><span class="hljs-string">:</span>
    <span class="hljs-attr">emitter-output-dir:</span> <span class="hljs-string">"{output-dir}/schema"</span>
    <span class="hljs-attr">openapi-versions:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-number">3.1</span><span class="hljs-number">.0</span>
</code></pre>
<p>Thanks to this configuration of the <code>tspconfig.yaml</code> file, one of TypeSpec's major assets is its ability to automatically generate OpenAPI specifications from clear, typed, and modular source code. This means you can write your API as you would in TypeScript (or a well-structured DSL), and get output in <code>.yaml</code> files compatible with the whole OpenAPI ecosystem: Swagger UI, Postman, Redoc, and so on.</p>
<p>In the next section, we'll look at the basic syntax of TypeSpec.</p>
<h2 id="heading-typespec-basic-syntax">TypeSpec Basic Syntax</h2>
<p>Now that you've got a clear idea of what TypeSpec is and what its benefits are in the world of API design, it's time to get to the heart of the matter: the basic syntax.</p>
<p>TypeSpec is a declarative language, inspired by TypeScript, that lets you model the resources, routes, data structures, and behaviors of an API in an explicit, readable, and modular way. Its syntax is based on simple keywords and clear file organization, making it easy to learn yet powerful.</p>
<h3 id="heading-language-basics">Language Basics</h3>
<p>Here's a very simple example of defining a model with TypeSpec:</p>
<pre><code class="lang-typescript">model Book {
  id: <span class="hljs-built_in">string</span>;
  title: <span class="hljs-built_in">string</span>;
  author: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>This block defines a <code>Book</code> resource with three typed fields. The <code>model</code> keyword is used to describe the JSON objects manipulated by the API. It is equivalent to schemas in JSON Schema or type definitions in OpenAPI.</p>
<h4 id="heading-defining-an-http-operation">Defining an HTTP operation</h4>
<p>TypeSpec lets you bind operations to models using the <code>@route</code> keyword. Here's a minimal example of an endpoint:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@route</span>(<span class="hljs-string">"/books"</span>)
op listBooks(): Book[];
</code></pre>
<p>This syntax declares a REST operation that returns a list of books. <code>@route</code> indicates the URL path, <code>op</code> introduces an operation, and <code>Book[]</code> is the return type.</p>
<p>You can also define path, query, or body parameters very easily.</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@route</span>(<span class="hljs-string">"/books/{id}"</span>)
op getBook(<span class="hljs-meta">@path</span> id: <span class="hljs-built_in">string</span>): Book;
</code></pre>
<p>In this example, we declare that <code>id</code> is a URL parameter (path parameter).</p>
<h3 id="heading-fundamental-concepts"><strong>Fundamental Concepts</strong></h3>
<h4 id="heading-model-defining-data-structures"><code>model</code> Defining data structures</h4>
<p>A <code>model</code> represents an API entity, like a JSON object. Models are the basis of your information exchanges.</p>
<pre><code class="lang-typescript">model User {
  id: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  age?: int32;
}
</code></pre>
<h4 id="heading-interface-group-operations"><code>interface</code> <strong>Group operations</strong></h4>
<p>An <code>interface</code> groups together a set of logically linked operations. This is useful for structuring large API sets.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> BookOperations {
  <span class="hljs-meta">@get</span> op listBooks(): Book[];
  <span class="hljs-meta">@get</span> op getBook(<span class="hljs-meta">@path</span> id: <span class="hljs-built_in">string</span>): Book;
}
</code></pre>
<h4 id="heading-service-entry-point-of-the-api"><code>service</code> <strong>Entry point of the API</strong></h4>
<p>A <code>service</code> defines publicly exposed interfaces, their version, and the basic path.</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@service</span>({ title: <span class="hljs-string">"Book API"</span>, version: <span class="hljs-string">"1.0.0"</span> })
<span class="hljs-keyword">namespace</span> BookApi {
  <span class="hljs-keyword">interface</span> BookOperations;
}
</code></pre>
<h3 id="heading-import-and-organize-your-code-with-namespaces"><strong>Import and Organize Your Code with Namespaces</strong></h3>
<p>TypeSpec provides clear organization through namespaces, similar to modules or packages.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">namespace</span> CommonModels {
  model <span class="hljs-built_in">Error</span> {
    message: <span class="hljs-built_in">string</span>;
  }
}
</code></pre>
<p>Then you can import them into another file like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> CommonModels <span class="hljs-keyword">from</span> <span class="hljs-string">"./common.tsp"</span>;
</code></pre>
<h3 id="heading-complete-example-of-a-rest-service"><strong>Complete Example of a REST Service</strong></h3>
<p>Let's take a complete example of a REST service in TypeSpec.</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@service</span>({ title: <span class="hljs-string">"Book Service"</span>, version: <span class="hljs-string">"1.0.0"</span> })

<span class="hljs-meta">@route</span>(<span class="hljs-string">"/books"</span>)

<span class="hljs-keyword">namespace</span> BookService {

  model Book {
    id: <span class="hljs-built_in">string</span>;
    title: <span class="hljs-built_in">string</span>;
    author: <span class="hljs-built_in">string</span>;
    publishedYear?: int32;
  }

  <span class="hljs-meta">@get</span>()
  op listBooks(): Book[];

  <span class="hljs-meta">@post</span>()
  op createBook(<span class="hljs-meta">@body</span> book: Book): Book;

  <span class="hljs-meta">@get</span>(<span class="hljs-string">"/{id}"</span>)
  op getBook(<span class="hljs-meta">@path</span> id: <span class="hljs-built_in">string</span>): Book;

  <span class="hljs-meta">@put</span>(<span class="hljs-string">"/{id}"</span>)
  op updateBook(<span class="hljs-meta">@path</span> id: <span class="hljs-built_in">string</span>, <span class="hljs-meta">@body</span> book: Book): Book;

  <span class="hljs-meta">@delete</span>(<span class="hljs-string">"/{id}"</span>)
  op deleteBook(<span class="hljs-meta">@path</span> id: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">void</span>;
}
</code></pre>
<p><strong>Here’s what’s going on</strong>:</p>
<ul>
<li><p><code>@service({ title, version })</code>: Defines service metadata (name, version), useful for generated documentation (for example, Swagger UI).</p>
</li>
<li><p><code>@route("/books")</code>: Defines the basic path for all operations of this API.</p>
</li>
<li><p><code>namespace BookService { ... }</code>: Encapsulates all models and operations linked to this service under a single logical name.</p>
</li>
</ul>
<p><strong>Next come the operations</strong>:</p>
<ul>
<li><p><code>@get() op listBooks()</code>: Endpoint <code>GET /books</code> qui retourne un tableau de livres.</p>
</li>
<li><p><code>@post() op createBook()</code>: Endpoint <code>POST /books</code> which accepts a <code>Book</code> object in the request body (<code>@body</code>) and returns the created book.</p>
</li>
<li><p><code>@get("/{id}")</code>: Endpoint <code>GET /books/{id}</code> which retrieves a book via its identifier (<code>@path</code>).</p>
</li>
<li><p><code>@put("/{id}")</code>: Endpoint <code>PUT /books/{id}</code> which updates a book's data.</p>
</li>
<li><p><code>@delete("/{id}")</code>: Deletes a book via its <code>id</code>. The <code>void</code> type means that no data is returned.</p>
</li>
</ul>
<p>With just a few lines, you get a complete, well-organized, easily readable REST service, ready to be automatically converted into OpenAPI documentation, a client SDK, or backend code.</p>
<h3 id="heading-add-validation-annotations"><strong>Add Validation Annotations</strong></h3>
<p>TypeSpec makes it easy to add validation annotations to your models using:</p>
<pre><code class="lang-typescript">model Book {
  id: <span class="hljs-built_in">string</span>;
  title: <span class="hljs-built_in">string</span> <span class="hljs-meta">@minLength</span>(<span class="hljs-number">3</span>);
  author: <span class="hljs-built_in">string</span> <span class="hljs-meta">@minLength</span>(<span class="hljs-number">3</span>);
  publishedYear?: int32 <span class="hljs-meta">@minValue</span>(<span class="hljs-number">1800</span>);
}
</code></pre>
<p>This adds validation rules directly to the schema, which will be taken into account during OpenAPI generation.</p>
<h3 id="heading-comparison-with-other-tools-openapi-swagger">Comparison with Other Tools (OpenAPI / Swagger)</h3>
<p>So you might wonder – why should you use TypeSpec rather than writing directly in OpenAPI?</p>
<p>Let's take the example of OpenAPI 3 (YAML):</p>
<pre><code class="lang-yaml"><span class="hljs-attr">paths:</span>
  <span class="hljs-string">/books:</span>
    <span class="hljs-attr">get:</span>
      <span class="hljs-attr">summary:</span> <span class="hljs-string">Get</span> <span class="hljs-string">list</span> <span class="hljs-string">of</span> <span class="hljs-string">books</span>
      <span class="hljs-attr">responses:</span>
        <span class="hljs-attr">'200':</span>
          <span class="hljs-attr">description:</span> <span class="hljs-string">OK</span>
          <span class="hljs-attr">content:</span>
            <span class="hljs-attr">application/json:</span>
              <span class="hljs-attr">schema:</span>
                <span class="hljs-attr">type:</span> <span class="hljs-string">array</span>
                <span class="hljs-attr">items:</span>
                  <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/Book'</span>
    <span class="hljs-attr">post:</span>
      <span class="hljs-attr">summary:</span> <span class="hljs-string">Create</span> <span class="hljs-string">a</span> <span class="hljs-string">new</span> <span class="hljs-string">book</span>
      <span class="hljs-attr">requestBody:</span>
        <span class="hljs-attr">content:</span>
          <span class="hljs-attr">application/json:</span>
            <span class="hljs-attr">schema:</span>
              <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/Book'</span>
      <span class="hljs-attr">responses:</span>
        <span class="hljs-attr">'201':</span>
          <span class="hljs-attr">description:</span> <span class="hljs-string">Created</span>
  <span class="hljs-string">/books/{id}:</span>
    <span class="hljs-attr">get:</span>
      <span class="hljs-attr">parameters:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">id</span>
          <span class="hljs-attr">in:</span> <span class="hljs-string">path</span>
          <span class="hljs-attr">required:</span> <span class="hljs-literal">true</span>
          <span class="hljs-attr">schema:</span>
            <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
      <span class="hljs-attr">responses:</span>
        <span class="hljs-attr">'200':</span>
          <span class="hljs-attr">description:</span> <span class="hljs-string">OK</span>
    <span class="hljs-attr">put:</span>
      <span class="hljs-attr">parameters:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">id</span>
          <span class="hljs-attr">in:</span> <span class="hljs-string">path</span>
          <span class="hljs-attr">required:</span> <span class="hljs-literal">true</span>
          <span class="hljs-attr">schema:</span>
            <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
      <span class="hljs-attr">requestBody:</span>
        <span class="hljs-attr">content:</span>
          <span class="hljs-attr">application/json:</span>
            <span class="hljs-attr">schema:</span>
              <span class="hljs-string">$ref:</span> <span class="hljs-string">'#/components/schemas/Book'</span>
    <span class="hljs-attr">delete:</span>
      <span class="hljs-attr">parameters:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">id</span>
          <span class="hljs-attr">in:</span> <span class="hljs-string">path</span>
          <span class="hljs-attr">required:</span> <span class="hljs-literal">true</span>
          <span class="hljs-attr">schema:</span>
            <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
<span class="hljs-attr">components:</span>
  <span class="hljs-attr">schemas:</span>
    <span class="hljs-attr">Book:</span>
      <span class="hljs-attr">type:</span> <span class="hljs-string">object</span>
      <span class="hljs-attr">properties:</span>
        <span class="hljs-attr">id:</span>
          <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
        <span class="hljs-attr">title:</span>
          <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
        <span class="hljs-attr">author:</span>
          <span class="hljs-attr">type:</span> <span class="hljs-string">string</span>
        <span class="hljs-attr">publishedYear:</span>
          <span class="hljs-attr">type:</span> <span class="hljs-string">integer</span>
</code></pre>
<p>As you can see, the OpenAPI definition is much more verbose. Relationships between paths, methods, schemas, and parameters are scattered, which complicates reading and maintenance. Also, it's less typed, given that OpenAPI remains YAML (or JSON), without the typing security or modularity of a real language.</p>
<h4 id="heading-why-typespec-is-useful-here">Why TypeSpec is useful here</h4>
<p>With TypeSpec, everything is centralized in a declarative, modular, typed, and intuitive format.</p>
<ul>
<li><p><strong>Greater legibility</strong>: less noise, more intent.</p>
</li>
<li><p><strong>Reusability</strong>: you can create modular components and share them between projects.</p>
</li>
<li><p><strong>Productivity</strong>: you write less code and generate more (OpenAPI, client, server, doc).</p>
</li>
<li><p><strong>Consistency</strong>: errors are detected early thanks to strong typing.</p>
</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Criteria</strong></td><td><strong>OpenAPI / Swagger</strong></td><td><strong>TypeSpec</strong></td></tr>
</thead>
<tbody>
<tr>
<td></td><td></td><td></td></tr>
<tr>
<td><strong>Syntax</strong></td><td>Verbose (YAML/JSON)</td><td>Declarative, typed, concise</td></tr>
<tr>
<td><strong>Organization</strong></td><td>Fragmented</td><td>Modular (namespace, import)</td></tr>
<tr>
<td><strong>Modular</strong></td><td>Limited</td><td>High (models, services)</td></tr>
<tr>
<td><strong>Built-in validation</strong></td><td>Separate or manual</td><td>Decorators (@minLength, and so on)</td></tr>
<tr>
<td><strong>Automatic generation</strong></td><td>Manual</td><td>Integrated (OpenAPI, SDK, and so on)</td></tr>
</tbody>
</table>
</div><p>Note: TypeSpec doesn't replace OpenAPI, but complements it: you write to TypeSpec, then automatically generate OpenAPI files, SDKs, specs and so on. It gives you a source language for accurately describing your API.</p>
<p>In the next section, we'll look at how to create a REST API template.</p>
<h2 id="heading-how-to-create-a-rest-api-model">How to Create a REST API Model</h2>
<p>To deepen our understanding of REST API creation with TypeSpec, let's continue with the example of managing books. In this example, we'll create a <code>Book</code> model, define a service to manage the books, and add validations to ensure that the data respects the right constraints.</p>
<h3 id="heading-define-a-data-model-for-book">Define a Data Model for <code>Book</code></h3>
<p>First, we'll define a data model for the Book resource. A book can have the following properties:</p>
<ul>
<li><p><code>id</code>: A unique identifier for the book.</p>
</li>
<li><p><code>title</code>: The title of the book.</p>
</li>
<li><p><code>author</code>: The author of the book.</p>
</li>
<li><p><code>publicationYear</code>: The book's year of publication.</p>
</li>
<li><p><code>isbn</code>: The book's ISBN number.</p>
</li>
</ul>
<p><code>Book</code> <strong>model in TypeSpec</strong></p>
<pre><code class="lang-typescript">model Book {
  id: integer;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  title: <span class="hljs-built_in">string</span>;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  author: <span class="hljs-built_in">string</span>;
  publicationYear: integer;
  <span class="hljs-meta">@pattern</span>(<span class="hljs-string">"^\\d{3}-\\d{1,5}-\\d{1,7}-\\d{1,7}-\\d{1}$"</span>)
  isbn: <span class="hljs-built_in">string</span>;
}
</code></pre>
<ul>
<li><p><code>id</code>: Unique book identifier (<code>integer</code> type).</p>
</li>
<li><p><code>title</code> and <code>author</code>: Character strings representing the book's title and author, validated by <code>@minLength(1)</code> to ensure they are not empty.</p>
</li>
<li><p><code>publicationYear</code>: The book's year of publication (<code>integer</code> type).</p>
</li>
<li><p><code>isbn</code>: The book's ISBN number, validated with a regular expression that matches the standard format of an ISBN.</p>
</li>
</ul>
<h3 id="heading-define-a-rest-service-to-manage-books">Define a REST Service to Manage Books</h3>
<p>Now that we have a <code>Book</code> model, we'll create a service to manage CRUD operations on this resource. This service will contain methods for retrieving a book by its identifier, creating a new book, updating an existing book, and deleting a book.</p>
<p><code>BooksService</code> <strong>service in TypeSpec</strong></p>
<pre><code class="lang-typescript">service BooksService {

  <span class="hljs-meta">@get</span>(<span class="hljs-string">"/books/{id}"</span>)
  getBook(id: integer): Book;

  <span class="hljs-meta">@post</span>(<span class="hljs-string">"/books"</span>)
  createBook(book: Book): Book;

  <span class="hljs-meta">@put</span>(<span class="hljs-string">"/books/{id}"</span>)
  updateBook(id: integer, book: Book): Book;

  <span class="hljs-meta">@delete</span>(<span class="hljs-string">"/books/{id}"</span>)
  deleteBook(id: integer): <span class="hljs-built_in">void</span>;
}
</code></pre>
<p>The <code>BooksService</code> contains four methods for performing actions on books:</p>
<ul>
<li><p><code>@get("/books/{id}")</code>: Method for retrieving a book by its <code>id</code>.</p>
</li>
<li><p><code>@post("/books")</code>: Method for creating a new book.</p>
</li>
<li><p><code>@put("/books/{id}")</code>: Method for updating an existing book by its <code>id</code>.</p>
</li>
<li><p><code>@delete("/books/{id}")</code>: Method for deleting a book based on its <code>id</code>.</p>
</li>
</ul>
<p>These methods use HTTP annotations to indicate the type of operation they perform (GET, POST, PUT, DELETE).</p>
<h3 id="heading-add-additional-validations-for-the-book-model"><strong>Add Additional Validations for the</strong> <code>Book</code> <strong>Model</strong></h3>
<p>As in the previous example for users, we can add additional validations on <strong>Book</strong> template properties.</p>
<p><strong>Example of validation on</strong> <code>publicationYear</code> <strong>and</strong> <code>isbn</code></p>
<pre><code class="lang-typescript">model Book {
  id: integer;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  title: <span class="hljs-built_in">string</span>;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  author: <span class="hljs-built_in">string</span>;
  <span class="hljs-meta">@minValue</span>(<span class="hljs-number">1000</span>)
  publicationYear: integer;
  <span class="hljs-meta">@pattern</span>(<span class="hljs-string">"^\\d{3}-\\d{1,5}-\\d{1,7}-\\d{1,7}-\\d{1}$"</span>)
  isbn: <span class="hljs-built_in">string</span>;
}
</code></pre>
<ul>
<li><p><code>@minValue(1000)</code> guarantees that the year of publication is greater than or equal to 1000.</p>
</li>
<li><p>Validation of the <code>isbn</code> remains the same, using a regular expression to validate a standard ISBN format.</p>
</li>
</ul>
<h3 id="heading-a-complete-service-for-managing-books"><strong>A Complete Service for Managing Books</strong></h3>
<p>Now that we have the <code>Book</code> model and the necessary validations, here's a complete service for managing books, with all the essential operations.</p>
<p><strong>Complete</strong> <code>BooksService</code> <strong>in TypeSpec</strong></p>
<pre><code class="lang-typescript">model Book {
  id: integer;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  title: <span class="hljs-built_in">string</span>;
  <span class="hljs-meta">@minLength</span>(<span class="hljs-number">1</span>)
  author: <span class="hljs-built_in">string</span>;
  <span class="hljs-meta">@minValue</span>(<span class="hljs-number">1000</span>)
  publicationYear: integer;
  <span class="hljs-meta">@pattern</span>(<span class="hljs-string">"^\\d{3}-\\d{1,5}-\\d{1,7}-\\d{1,7}-\\d{1}$"</span>)
  isbn: <span class="hljs-built_in">string</span>;
}

service BooksService {
  <span class="hljs-meta">@get</span>(<span class="hljs-string">"/books/{id}"</span>)
  getBook(id: integer): Book;

  <span class="hljs-meta">@post</span>(<span class="hljs-string">"/books"</span>)
  createBook(book: Book): Book;

  <span class="hljs-meta">@put</span>(<span class="hljs-string">"/books/{id}"</span>)
  updateBook(id: integer, book: Book): Book;

  <span class="hljs-meta">@delete</span>(<span class="hljs-string">"/books/{id}"</span>)
  deleteBook(id: integer): <span class="hljs-built_in">void</span>;
}
</code></pre>
<ul>
<li><p>The <code>Book</code> model defines properties and validations for a book.</p>
</li>
<li><p>The <code>BooksService</code> provides endpoints for retrieving, creating, updating, and deleting a book.</p>
</li>
<li><p>Each service method is correctly annotated with the corresponding HTTP verbs (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>).</p>
</li>
</ul>
<p>And here’s a summary of everything we’ve done:</p>
<ul>
<li><p>We created a <code>Book</code> model with properties such as title, author, year of publication, and ISBN number.</p>
</li>
<li><p>We defined a <code>BooksService</code> to provide CRUD operations on books.</p>
</li>
<li><p>We added validations to ensure that the data respected specified constraints (for example, ISBN and year of publication).</p>
</li>
<li><p>We designed a complete REST API to manage books with TypeSpec, using a minimum amount of code and staying true to standards.</p>
</li>
</ul>
<p>This example shows just how quickly and efficiently TypeSpec can be used to model a REST API, while ensuring a clear structure and robust validations.</p>
<h2 id="heading-how-to-build-the-api-in-express-and-aspnet-core">How to Build the API in Express and ASP.NET Core</h2>
<p>Now that we've defined a book management REST service with TypeSpec, let's see how we'd implement this same API using two popular frameworks:</p>
<ul>
<li><p><strong>ExpressJS (Node.js / TypeScript)</strong></p>
</li>
<li><p><strong>ASP.NET Core (C#)</strong></p>
</li>
</ul>
<p>This will allow us to better compare TypeSpec's conciseness and readability with traditional implementations.</p>
<p><strong>Manual implementation with ExpressJS (Node.js / TypeScript):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">//server.ts</span>
<span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;

<span class="hljs-keyword">const</span> app = express();
app.use(express.json());

<span class="hljs-keyword">interface</span> Book {
  id: <span class="hljs-built_in">number</span>;
  title: <span class="hljs-built_in">string</span>;
  author: <span class="hljs-built_in">string</span>;
  publicationYear: <span class="hljs-built_in">number</span>;
  isbn: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> books: Book[] = [];

<span class="hljs-comment">// GET /books/:id</span>
app.get(<span class="hljs-string">'/books/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">parseInt</span>(req.params.id);
  <span class="hljs-keyword">const</span> book = books.find(<span class="hljs-function"><span class="hljs-params">b</span> =&gt;</span> b.id === id);
  <span class="hljs-keyword">if</span> (!book) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send({ message: <span class="hljs-string">'Book not found'</span> });
  res.send(book);
});

<span class="hljs-comment">// POST /books</span>
app.post(<span class="hljs-string">'/books'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> newBook: Book = req.body;
  books.push(newBook);
  res.status(<span class="hljs-number">201</span>).send(newBook);
});

<span class="hljs-comment">// PUT /books/:id</span>
app.put(<span class="hljs-string">'/books/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">parseInt</span>(req.params.id);
  <span class="hljs-keyword">const</span> index = books.findIndex(<span class="hljs-function"><span class="hljs-params">b</span> =&gt;</span> b.id === id);
  <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send({ message: <span class="hljs-string">'Book not found'</span> });

  books[index] = req.body;
  res.send(books[index]);
});

<span class="hljs-comment">// DELETE /books/:id</span>
app.delete(<span class="hljs-string">'/books/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">parseInt</span>(req.params.id);
  <span class="hljs-keyword">const</span> index = books.findIndex(<span class="hljs-function"><span class="hljs-params">b</span> =&gt;</span> b.id === id);
  <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send({ message: <span class="hljs-string">'Book not found'</span> });

  books.splice(index, <span class="hljs-number">1</span>);
  res.status(<span class="hljs-number">204</span>).send();
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);
});
</code></pre>
<p><strong>Observations:</strong></p>
<ul>
<li><p>A lot of repetitive logic.</p>
</li>
<li><p>No automatic validation.</p>
</li>
<li><p>Routes must be maintained manually.</p>
</li>
<li><p>No automatically generated API documentation.</p>
</li>
</ul>
<p><strong>Manual implementation with</strong> <a target="_blank" href="http://ASP.NET"><strong>ASP.NET</strong></a> <strong>Core (C#):</strong></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Book.cs</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;

    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Author { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;

    [<span class="hljs-meta">Range(1000, int.MaxValue)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> PublicationYear { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">RegularExpression(@<span class="hljs-meta-string">"^\d{3}-\d{1,5}-\d{1,7}-\d{1,7}-\d{1}$"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Isbn { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-comment">// BooksController.cs</span>
[<span class="hljs-meta">ApiController</span>]
[<span class="hljs-meta">Route(<span class="hljs-meta-string">"books"</span>)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BooksController</span> : <span class="hljs-title">ControllerBase</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> List&lt;Book&gt; books = <span class="hljs-keyword">new</span>();

    [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"{id}"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">GetBook</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">var</span> book = books.FirstOrDefault(b =&gt; b.Id == id);
        <span class="hljs-keyword">if</span> (book == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> NotFound(<span class="hljs-string">"Book not found"</span>);
        <span class="hljs-keyword">return</span> Ok(book);
    }

    [<span class="hljs-meta">HttpPost</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">CreateBook</span>(<span class="hljs-params">[FromBody] Book book</span>)</span>
    {
        books.Add(book);
        <span class="hljs-keyword">return</span> CreatedAtAction(<span class="hljs-keyword">nameof</span>(GetBook), <span class="hljs-keyword">new</span> { id = book.Id }, book);
    }

    [<span class="hljs-meta">HttpPut(<span class="hljs-meta-string">"{id}"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">UpdateBook</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id, [FromBody] Book updatedBook</span>)</span>
    {
        <span class="hljs-keyword">var</span> index = books.FindIndex(b =&gt; b.Id == id);
        <span class="hljs-keyword">if</span> (index == <span class="hljs-number">-1</span>) <span class="hljs-keyword">return</span> NotFound(<span class="hljs-string">"Book not found"</span>);

        books[index] = updatedBook;
        <span class="hljs-keyword">return</span> Ok(updatedBook);
    }

    [<span class="hljs-meta">HttpDelete(<span class="hljs-meta-string">"{id}"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">DeleteBook</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">var</span> book = books.FirstOrDefault(b =&gt; b.Id == id);
        <span class="hljs-keyword">if</span> (book == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> NotFound(<span class="hljs-string">"Book not found"</span>);

        books.Remove(book);
        <span class="hljs-keyword">return</span> NoContent();
    }
}
</code></pre>
<p><strong>Observations:</strong></p>
<ul>
<li><p>More formal and structured than Express, thanks to C# annotations (<code>[HttpPost]</code>, <code>[Required]</code>, and so on).</p>
</li>
<li><p>Validation is handled automatically via Data Annotations.</p>
</li>
<li><p>Once again, no automatic OpenAPI generation or SDK client without additional configuration.</p>
</li>
</ul>
<p><strong>Comparison with TypeSpec:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Aspect</strong></td><td><strong>TypeSpec</strong></td><td><strong>ExpressJS</strong></td><td><a target="_blank" href="http://ASP.NET"><strong>ASP.NET</strong></a> <strong>Core</strong></td></tr>
</thead>
<tbody>
<tr>
<td></td><td></td><td></td><td></td></tr>
<tr>
<td><strong>Syntax</strong></td><td>Declarative</td><td>Imperative</td><td>Structured</td></tr>
<tr>
<td><strong>Validation</strong></td><td>Automatic</td><td>Manual</td><td>Data Annotations</td></tr>
<tr>
<td><strong>Documentation</strong></td><td>Automatic</td><td>Manual</td><td>Generated(Swashbuckle)</td></tr>
<tr>
<td><strong>Reusability</strong></td><td>High</td><td>Low</td><td>Medium</td></tr>
<tr>
<td><strong>Generation</strong></td><td>OpenAPI/SDK</td><td>Non-native</td><td>Possible</td></tr>
</tbody>
</table>
</div><h2 id="heading-best-practices-for-structuring-typespec-projects-and-components">Best Practices for Structuring TypeSpec Projects and Components</h2>
<p>When you start writing API definitions in TypeSpec, it's easy to put everything in a single file. But as with any software project, as the application grows, a good structure becomes essential to guarantee the readability, reusability and maintainability of the code.</p>
<p>Here's a set of best practices I strongly recommend:</p>
<h3 id="heading-organize-by-functional-area"><strong>Organize by Functional Area</strong></h3>
<p>Use namespaces to group models, interfaces, and operations by business domain: <strong>book</strong>, <strong>user</strong>, <strong>auth</strong>, <strong>payment</strong>, and so on.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">namespace</span> MyApi.Books;
</code></pre>
<p>Create a <code>/books</code> folder with the following files:</p>
<pre><code class="lang-yaml"><span class="hljs-string">src/</span>
<span class="hljs-string">├──</span> <span class="hljs-string">books/</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">models.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">routes.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">service.tsp</span>
</code></pre>
<p>This ensures a clear separation of responsibilities, just like in a well-structured Node.js project.</p>
<h3 id="heading-a-single-maintsp-entry-point"><strong>A Single</strong> <code>main.tsp</code> <strong>Entry Point</strong></h3>
<p>This is the main file that orchestrates:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// main.tsp</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"./books/service.tsp"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./users/service.tsp"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./auth/service.tsp"</span>;
</code></pre>
<p>This allows you to compile the entire project from a single point.</p>
<h3 id="heading-create-reusable-components">Create Reusable Components</h3>
<p>Define common models and types in a shared file. Example:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// common/models.tsp</span>
model ErrorResponse {
  code: <span class="hljs-built_in">string</span>;
  message: <span class="hljs-built_in">string</span>;
}

<span class="hljs-meta">@defaultResponse</span>
op <span class="hljs-built_in">Error</span>(): ErrorResponse;
</code></pre>
<p>Then import them into your other files:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">"../common/models.tsp"</span>;
</code></pre>
<p>This is handy for centralizing errors, standard answers, pagination types, and so on.</p>
<h3 id="heading-use-decorators-to-enrich-your-components">Use Decorators to Enrich Your Components</h3>
<p>Decorators such as <code>@doc</code>, <code>@minLength</code>, <code>@server</code>, <code>@route</code> or <code>@tag</code> can be used to generate valid, documented APIs without any extra effort:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@route</span>(<span class="hljs-string">"/books"</span>)
<span class="hljs-meta">@doc</span>(<span class="hljs-string">"Get all books"</span>)
op listBooks(): Book[];
</code></pre>
<p>A well-annotated API is one that is ready for automatic generation of documentation or clients.</p>
<h3 id="heading-define-servers-in-the-right-place">Define Servers in the Right Place</h3>
<p>Add your @server directive to a <code>service.tsp</code> or global <code>api.tsp</code> file:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@server</span>(<span class="hljs-string">"Production"</span>, <span class="hljs-string">"https://api.mysite.com"</span>)
<span class="hljs-meta">@server</span>(<span class="hljs-string">"Staging"</span>, <span class="hljs-string">"https://staging.mysite.com"</span>)
</code></pre>
<p>This allows you to target different environments without duplicating definitions.</p>
<h3 id="heading-validate-regularly">Validate Regularly</h3>
<p>Integrate <code>tsp compile</code> into your CI/CD to ensure that your definitions are always valid. Example with an npm script:</p>
<pre><code class="lang-bash">npm run tsp compile src/main.tsp --emit=./dist
</code></pre>
<p>This avoids last-minute errors and guarantees the consistency of your API over time.</p>
<p><strong>Example of a recommended complete structure:</strong></p>
<pre><code class="lang-yaml"><span class="hljs-string">project-root/</span>
<span class="hljs-string">├──</span> <span class="hljs-string">src/</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">books/</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">models.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">routes.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">service.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">users/</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">models.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">service.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">common/</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">models.tsp</span>
<span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">main.tsp</span>
<span class="hljs-string">├──</span> <span class="hljs-string">tspconfig.yaml</span>
<span class="hljs-string">├──</span> <span class="hljs-string">package.json</span>
<span class="hljs-string">└──</span> <span class="hljs-string">README.md</span>
</code></pre>
<p>In summary:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Good practice</strong></td><td><strong>Why it's important</strong></td></tr>
</thead>
<tbody>
<tr>
<td></td><td></td></tr>
<tr>
<td>Use <code>namespaces</code></td><td>Clear organization, readability</td></tr>
<tr>
<td>Dividing files by domain</td><td>Reusability, modularity</td></tr>
<tr>
<td>Centralize shared components</td><td>DRY (Don't Repeat Yourself)</td></tr>
<tr>
<td>Use decorators</td><td>Enrich documentation and validation</td></tr>
<tr>
<td>Integrate with CI/CD</td><td>Continuous quality, no surprises</td></tr>
<tr>
<td>Have a clear input file (<code>main.tsp</code>)</td><td>Simple, centralized compilation</td></tr>
</tbody>
</table>
</div><h2 id="heading-conclusion">Conclusion</h2>
<p>TypeSpec represents a real evolution in the way we design, document and maintain APIs. By adopting a declarative, modular, and typed approach, it simplifies the definition of APIs while enhancing their quality, readability, and consistency on a large scale.</p>
<p>Whether you're a front-end developer consuming APIs, a software architect looking to standardize your team's practices, or a technical documentation enthusiast, TypeSpec offers you a robust, modern, and extensible solution.</p>
<p>The TypeSpec ecosystem is still young but very promising, supported by Microsoft and used internally on a large scale. So now's the time to start exploring and adopting it for your projects.</p>
<h4 id="heading-ressources">Ressources</h4>
<ol>
<li><p><strong>TypeSpec official website</strong><br> <a target="_blank" href="https://typespec.io/">https://typespec.io</a><br> Full documentation, guides, syntax references and APIs.</p>
</li>
<li><p><strong>TypeSpec GitHub repository (Microsoft)</strong><br> <a target="_blank" href="https://github.com/microsoft/typespec/">https://github.com/microsoft/typespec</a><br> Source code, examples and community discussions.</p>
</li>
<li><p><strong>Playground TypeSpec (essayer dans le navigateur)</strong><br> <a target="_blank" href="https://typespec.io/playground/">https://typespec.io/playground</a><br> Quickly test your models without installing anything.</p>
</li>
<li><p><strong>TypeSpec documentation — Microsoft Learn</strong><br> <a target="_blank" href="https://learn.microsoft.com/en-us/azure/developer/typespec/overview/">https://learn.microsoft.com/en-us/azure/developer/typespec/overview</a><br> Learn how to use TypeSpec to create consistent, high-quality APIs efficiently and integrate them seamlessly with existing toolchains.</p>
</li>
<li><p><strong>OpenAPI Specification</strong><br> <a target="_blank" href="https://swagger.io/specification/">https://swagger.io/specification</a><br> To compare with current API description standards.</p>
</li>
<li><p><strong>TypeSpec 101 by Mario Guerra Product Manager for TypeSpec at Microsoft</strong><br> <a target="_blank" href="https://www.youtube.com/playlist?list=PLYWCCsom5Txglkl_I1XvwzrzM5G3SuVsR/">https://www.youtube.com/playlist?list=PLYWCCsom5Txglkl_I1XvwzrzM5G3SuVsR</a><br> A tutorial series, hosted by Mario Guerra, TypeSpec product manager at Microsoft, will guide you through the process of building a REST API using TypeSpec, and generating an OpenAPI specification from our code.</p>
</li>
<li><p><strong>APIs at Scale with TypeSpec</strong><br> <a target="_blank" href="https://youtu.be/yfCYrKaojDo/">https://youtu.be/yfCYrKaojDo</a><br> A talk given by Mandy Whaley from Microsoft at the 2024 Austin API Summit in Austin, Texas.</p>
</li>
</ol>
<p>Thanks for reading. You can find me on <a target="_blank" href="https://www.linkedin.com/in/AdalbertPungu/">LinkedIn</a>, and follow me on all socials @AdalbertPungu.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
