Skip to content
Snippets Groups Projects
development.md 2.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • # Development Notes
    
    ## Adding Endpoints to the API
    
    The api package contains the code for the API from which swagger definitions are automatically generated. We're using a simple golang echo server to serve the API. In `api/api.go` you can add new endpoints by registering new routes for a path with a matching handler. 
    
    ### Simple Example
    Let's assume we want to add a new imaginary service endpoint. Amend the following line to `func InitServer(cfg *Config) *echo.Echo`:
    
    ```
    e.GET("api/newservice", r.GetNewService)
    ```
    
    `r` is of type `api.registry` which holds the main information of our service and contains the methods to aggregate the response data for the request. 
    
    Create a new method that serves the response 
    
    ```
    func (r *registry) GetNewService(c echo.Context) error {
        // TODO: add service's logic here 
        // and replace nil with the json formatted struct you want to return
        return c.JSON(http.StatusOK, nil)
    }
    ```
    
    It's important to add godoc to the new method, so that swagger definitions will be correctly generated.
    
    Add above the function `func (r *registry) GetNewService(c echo.Context) error`
    ```
    // NewService godoc
    // @Summary      <Short summary about the endpoints purpose>
    // @Description  <Longer description what the endpoint offers.>
    // @Tags         Provisioning
    // @Accept       json
    // @Produce      json
    // @Param        serviceparam	query  string false "query parameter description"
    // @Success      200  {object}  models.NewServiceModel
    // @Failure      400  {object}  error
    // @Failure      404  {object}  error
    // @Failure      500  {object}  error
    // @Router       /api/newService [get]
    ```
    
    More descriptions about each annotation can be found [here](https://github.com/swaggo/swag?tab=readme-ov-file#api-operation).
    
    Let's assume the response body is a json which can be serialized to `models.NewServiceModel`. Create a  new struct in `models/resources.go` 
    
    ```
    // Describe the struct model
    type NewServiceModel struct {
    	// Describe each field of your struct
    	Property1 string `json:"property1,omitempty"`
    }
    ```
    
    The comments above the struct and each field will be added as descriptions to the swagger definition.
    
    
    Finally ensure that you return an instance of this struct in `func (r *registry) GetNewService(c echo.Context) error` instead of nil.
    
    To generate / updated the swagger definitions you can proceed now with the [OpenAPI spec generation](../README.md#openapi-spec-generation) section.