You're right to notice the mismatch between your docstring and your code! The docstring // @Failure 500 {object} entities.APIError tells the documentation generator (like Swag) to expect a response body shaped like the entities.APIError struct. However, your code c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) returns a simple JSON object with a single key, "error".
To accurately document the response your code is actually sending, you have a couple of options using Swag annotations:
Option 1: Define a simple struct that matches the gin.H structure and use it in the docstring (Recommended)
This is the most common and clearest approach. You define a struct that mirrors the JSON structure returned by gin.H.
Define the struct: Create a simple struct (you can define it in the same file or a common responses package if you have many such errors).
go
// ErrorResponse represents the structure of a generic error response.
type ErrorResponse struct {
Error string `json:"error"` // The error message
}
(Note: The json:"error" tag is important for Swag to map the struct field to the JSON key).
Update the docstring: Use this new struct in your @Failure annotation.
go
// @Failure 500 {object} ErrorResponse "Internal Server Error"
This tells Swag that on a 500 error, the response body will be a JSON object matching the ErrorResponse struct, which correctly describes your gin.H{"error": ...}.
Option 2: Describe the object inline (Less common for objects, but possible if the tool supports it)
Some tools might allow describing simple inline objects, but defining a struct is generally more robust and maintainable, especially if the error structure grows or is reused. Swag primarily relies on Go types for object definitions. While you might see examples for simple types or arrays, describing an object's internal structure directly in the docstring without a corresponding Go type is less standard for tools like Swag.
Why Option 1 is preferred:
Clarity: It explicitly defines the structure of the error response using a Go type, which is easy to understand and maintain.
Consistency: Promotes using defined types for API responses, even for errors.
Tool Compatibility: Swag is designed to work well with Go types ({object} YourStruct).
In summary: The best way to describe your c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return in your docstring for a tool like Swag is to define a Go struct that matches the {"error": "..."} structure and reference that struct in your @Failure 500 annotation.
User
can it be just // @Failure 400 {object} map[string]any?
Assistant
Yes, you can technically use // @Failure 400 {object} map[string]any (or map[string]interface{} depending on your Go version/preference) in your docstring.
What this means in the documentation:
When a tool like Swag processes this, it will typically generate documentation that indicates the response for a 400 error is a generic JSON object (like OpenAPI type: object) where the keys are strings and the values can be of any type.
Pros:
It correctly reflects that the underlying Go type being marshaled to JSON is a map.
Cons:
Less Informative: This is the main drawback. It doesn't tell the API consumer anything about the structure of the map. It doesn't specify that there will be an "error" key, or that its value will be a string.
Lack of Specificity: If your gin.H always contains specific keys (like "error"), using map[string]any hides this crucial information. The documentation should tell consumers exactly what data they can expect.
Recommendation:
While map[string]any works from a technical standpoint of matching the Go type, it is generally less helpful for API consumers than defining a specific struct.
If your error response is consistently in the format {"error": "some message"}, defining a small struct like:
go
// GenericErrorResponse represents a common error response structure.
type GenericErrorResponse struct {
Error string `json:"error"`
}
And then using // @Failure 400 {object} GenericErrorResponse "Bad Request" is much better documentation. It clearly tells the consumer: "On a 400 error, you will receive a JSON object with a single field named 'error', and its value will be a string."
Use map[string]any only if:
The structure of the map is truly arbitrary and unpredictable (which is rare for structured API error responses).
You absolutely cannot define a specific struct for some reason.
For the vast majority of cases where your gin.H or map has a known, consistent structure (like containing an "error" key), defining and using a struct is the recommended best practice for clearer documentation.
User
if i have entity with foreign key to another entity
and another entity is not found? what http error shoul i return?
// Conflict 409
// Unprocessable Entity 422
Assistant
Based on standard API practices and the definitions of these HTTP status codes, the most appropriate status code to return when a foreign key reference points to a non-existent entity is 422 Unprocessable Entity.
Here's why:
422 Unprocessable Entity (RFC 4918): This status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.
In your case, the request (e.g., creating an entity with a specific foreign key ID) is syntactically correct. However, the instruction within the request (linking to an entity with that ID) cannot be processed because the referenced entity does not exist. This is a semantic error in the request data, making the entity "unprocessable".
409 Conflict: This status code indicates a conflict with the current state of the target resource.
While there is a "conflict" in the sense that you can't create the link, 409 is more commonly used for conflicts related to the state of the resource you are trying to modify (e.g., trying to update a resource based on an outdated version, or trying to create a resource that already exists with a unique constraint). The conflict here isn't primarily with the state of the target resource itself, but with the validity of the input data referencing another non-existent resource.
In summary:
Use 422 Unprocessable Entity to indicate that the request payload contains semantic errors, specifically that a referenced resource (via a foreign key) does not exist. This is a precise description of the problem.
While you could argue for 400 Bad Request as a generic client error, 422 provides more specific information about why the request was bad (it's semantically incorrect/unprocessable due to invalid data referencing another resource).
Avoid 409 Conflict for this specific scenario, as its primary use case is for conflicts related to the state of the resource being acted upon, or concurrent modifications.
When returning 422, your response body should clearly explain which field (the foreign key) is invalid and why (the referenced entity does not exist). For example:
json
{
"error": "Unprocessable Entity",
"details": "The referenced entity with ID X for field 'foreign_key_field_name' does not exist."
}