We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Create User

We've written the SQL query, now it's time to write the API handler that will allow users to create a new user.

Assignment

  1. Request:

    {
      "email": "user@example.com"
    }
    

    Response:

    HTTP 201 Created

    {
      "id": "50746277-23c6-4d85-a890-564c0044c2fb",
      "created_at": "2021-07-07T00:00:00Z",
      "updated_at": "2021-07-07T00:00:00Z",
      "email": "user@example.com"
    }
    

    Your SQLC CreateUser method expects a context.Context as its first argument. In an HTTP handler, use the request context from r.Context().

Run and submit the CLI tests.

Tips

I created a User struct in my main package. When the database package returns a database.User, I map it to my main package's User struct before marshalling it to JSON so that I can control the JSON keys:

type User struct {
	ID        uuid.UUID `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Email     string    `json:"email"`
}

Alternatively, you can use the emit_json_tags configuration option to automatically include the JSON tags. However, in larger projects, this may be more restrictive than useful.