Unprocessable entity error

I have created a post Api in go giber to to create a prompt. From the frontend I am passing the payload creator which has a string type but in my prompt_model i have it as prmitive.ObjectId type.
when I am running the function c.BodyParser(&prompt) it throws the error bad request Unprocessable Entity.

Here is the Prompt model:

type Prompts struct{
	Id primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
	Creator primitive.ObjectID `json:"creator,omitempty" bson:"creator,omitempty"`
	CreatorUser User `json:"creatorUser,omitempty" bson:"-"`
	Prompt string `json:"prompt,omitempty" validate:"required"`
	Tag string `json:"tag,omitempty" validate:"required"`
}

here is the code for create-prompt controller:

func CreatePrompt(c *fiber.Ctx) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	var prompt models.Prompts

	// Extract session ID from the URL parameter
	// sessionID := c.FormValue("creator")
	// sessionObjectID, _ := primitive.ObjectIDFromHex(sessionID)
	// fmt.Printf("ss %v \n ",sessionID)

	// Validate the request body
	fmt.Println("dd", c.BodyParser(&prompt))
	if err := c.BodyParser(&prompt); err != nil {
		return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{
			Status:  http.StatusBadRequest,
			Message: "error",
			Data:    &fiber.Map{"data": err.Error()},
		})
	}

	// Assuming the session ID is stored in the Creator field
	newPrompt := models.Prompts{
		Id:          primitive.NewObjectID(),
		Creator:     prompt.Creator,
		Prompt:      prompt.Prompt,
		Tag:         prompt.Tag,
	}

	result, err := promptCollection.InsertOne(ctx, newPrompt)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(responses.UserResponse{
			Status:  http.StatusInternalServerError,
			Message: "error",
			Data:    &fiber.Map{"data": err.Error()},
		})
	}

	return c.Status(http.StatusCreated).JSON(responses.UserResponse{
		Status:  http.StatusCreated,
		Message: "success",
		Data:    &fiber.Map{"data": result},
	})
}

here is the api call from frontend:

const response = await fetch("http://localhost:8000/create-prompt", {
        method: "POST",
        body: JSON.stringify({
          creator: session?.user.id,
          prompt: post.prompt,
          tag: post.tag,
        }),

here is the log for the payload data:

{
  "creator":"64ea57ad19b714af26ef3756",
  "prompt":"ads",
   "tag":"as"
}

I tried to convert the creator from string type to objectId type before using the bodyParser method but it was in vein
what I am doing wrong exactly?

I tried to reproduce the problem and here what I have found.

  1. Please, check the code and confirm that I used the correct packages and didn’t break the logic:
package main

import (
	"fmt"

	fiber "github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type Prompts struct {
	Id      primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
	Creator primitive.ObjectID `json:"creator,omitempty" bson:"creator,omitempty"`
	Prompt  string             `json:"prompt,omitempty" validate:"required"`
	Tag     string             `json:"tag,omitempty" validate:"required"`
}

func CreatePrompt(c *fiber.Ctx) error {
	var prompt Prompts

	// Validate the request body
	fmt.Println("dd", c.BodyParser(&prompt))
	if err := c.BodyParser(&prompt); err != nil {
		return err
	}

	// Assuming the session ID is stored in the Creator field
	newPrompt := Prompts{
		Id:      primitive.NewObjectID(),
		Creator: prompt.Creator,
		Prompt:  prompt.Prompt,
		Tag:     prompt.Tag,
	}

	fmt.Printf("%#v\n", newPrompt)

	return nil
}

func main() {
	f := fiber.New()

	f.Post("/test", CreatePrompt)

	f.Listen(":8080")
}
  1. If everything is okay. I ran this application and tried to use Postman to send a Post request with body:

And the response was the same error, you got Unprocessable Entity.

  1. After the debug of the c.BodyParser func I found the possible problem: the type of the body “text/plain” is actually not supported by the parser. But as soon as I changed the body type within my Postman request to “application/json”, it worked as intended without an error. My guess is to add contentType: 'application/json', to your frontend call to specify it explicitly.
1 Like

Thanks it did work fine, you are life saver

Hi it worked but I still have a slight problem


in this as you can see I want the creator field to be populated by the user Id from the user collection to refernce the user object like in the first part but I am not getting the creator field as you can see in the second document

Can you share the code you use for this?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.