C83 / THP_2.0

0 stars 0 forks source link

Create the lesson controller #9

Closed C83 closed 6 years ago

C83 commented 6 years ago

Why ?

Finally a controller so we can talk to the outer world \o/

We will use ActiveModel Serializer as it allows us to separate our concern. Its neither the role of a model nor a controller to take care of how to serialize as Json a model.

We will use Postman as a way to generate playable documentation and also to test manually our API.

Our API will be nicely constructed and will return nice errors and proper http response code.

Must have

Todo

Serializer

Controller

Test it with Postman

Create one for this app it will help you a lot.

Test it with Rspec

API spec

{
  "lesson": {
    "title": "my title",
    "description": "my description"
  }
}

GET on / Returns a list of serialized lessons. Respond with a 200

POST on / Creates a new lesson and returns it. Respond with a 201

If the lesson is not valid, or if there's a missing param, it should return a error message with the actual error and respond with a 403.

(You should validate params with rails strong parameters and add a rescue_from in app/controllers/application.rb)

GET on /:id Returns the right lesson. Respond with a 200. If the lesson can't be found, respond with a proper error and a 404. (For this I advise you add a rescue_from in app/controllers/application.rb)

PATCH on /:id Update the lesson and returns it. Respond with a 200. Same errors as create

DELETE on /:id Delete the right lesson. Respond with a 204 If the lesson doesn't exist, respond with a 404.

Reading List

C83 commented 6 years ago

Controller

Serializer :

Add Serializer gem in Gemfile :

## Serializer
gem 'active_model_serializers', '~> 0.10.0

Then, bundle install Generating the serializer for lesson model : rails g serializer lesson After that, you can specify attributes you want render :

attributes :id, :title, :description, :created_at

Now, it's easy because we have no association.

Routes

We use the keyword ressources in the route.rb file :

resources :lessons, except: [:new, :edit]

Testing the last step with rails routes

Controller

Create a controller with this ressource. As read, ApplicationController is the right controller for API.

Error :

We want that an error raises up when params aren't valid. create!() permit that : if validation doesn't work, ActiveRecord::RecordInvalid: Validation failed: raises. Place that in application.rb file :

  # Two errors catched : RecordInvalid and ParameterMissing
  rescue_from ActiveRecord::RecordInvalid, ActionController::ParameterMissing, with: :show_errors

  def show_errors(exception)
    render json: exception, status: 403
  end

Render :

To return, use render json: object, status number. Replace with the correct object who has a serializer. Add the correspondent status (the number or the name).

Test controller :

Some tips :