The first endpoint – REST APIs

The code of the first endpoint that allows a client to read an entity looks like this:

app.MapGet(
    “/{id:int}”,
    (int id) => new ReadOneDto(
        id,
        “John Doe”
    )
);
public record class ReadOneDto(int Id, string Name);

Here’s the API contract we can extract from the preceding code:

Contract segmentValue
HTTP MethodGET
URI/{id} (for example, /123 )
InputThe id parameter
OutputAn instance of the ReadOneDto class.

Sending the following HTTP request (you can use the ReadOneEntity.http file) results in the output that follows:

GET /123 HTTP/1.1
Accept: application/json
Host: localhost:7000
Connection: keep-alive

The trimmed-down response is:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Sat, 03 Jun 2023 17:41:42 GMT
Server: Kestrel
Alt-Svc: h3=”:7000″; ma=86400
Transfer-Encoding: chunked
 
{“id”:123,”name”:”John Doe”}

As we can see, when we query the API for the entity id=123, the endpoint returns that entity with a 200 OK status code, and the response body is a serialized instance of the ReadOneDto class.

The .http files are new to VS 2022 and allow us to write and execute HTTP requests from VS itself. I left a link in the Further Reading section if you want to know more.

SwaggerGen generated the following OpenAPI specs for the first endpoint:

“/{id}”: {
  “get”: {
    “parameters”: [
      {
        “name”: “id”,
        “in”: “path”,
        “required”: true,
        “schema”: {
          “type”: “integer”,
          “format”: “int32”
        }
      }
    ],
    “responses”: {
      “200”: {
        “description”: “Success”,
        “content”: {
          “application/json”: {
            “schema”: {
              “$ref”: “#/components/schemas/ReadOneDto”
            }
          }
        }
      }
    }
  }
},

That snippet describes the endpoint and references our output model (highlighted line). The schemas are at the bottom of the JSON file. Here’s the schema that represents the ReadOneDto:

“ReadOneDto”: {
  “type”: “object”,
  “properties”: {
    “id”: {
      “type”: “integer”,
      “format”: “int32”
    },
    “name”: {
      “type”: “string”,
      “nullable”: true
    }
  },
  “additionalProperties”: false
}

As we can see from the highlighted lines, that schema has a property name of type string and a property id of type integer, the same as our ReadOneDto class. Fortunately, we don’t need to write that JSON since the tool generates it based on our code. Next, we look at the second endpoint.

You may also like