alisontague
alisontague

Reputation: 329

API POST request returns 404 route not found

Rails 5.2.2.1 ruby 2.6.3p62

I'm writing an API endpoint that should accept a post request. I created the route:

namespace :api do
   scope module: :v1, constraints: Example::ApiVersionConstraint.new(1) do
     resources 'books', only: [:create]
   end
 end

bundle exec rails routes | grep books returns:

api_books POST /api/books(.:format) api/v1/books#create

app/controllers/api/v1/books_controller.rb:

class Api::V1::BooksController < Api::BaseController
   attr_reader :book

   def create
      book = Book.build(title: 'test')

      if book.save
         render json: book
      else
         render json: { error: 'error' }, status: 400
      end
   end
end

server is running on port 3000 and when submitting a POST request to http://localhost:3000/api/books.json using Postman I get this response:

{
"errors": [
    {
        "code": "routing.not_found",
        "status": 404,
        "title": "Not found",
        "message": "The path '/api/books' does not exist."
    }
],
"request": ""
}

lib/example/api_version_constraint.rb:

module Example
  class ApiVersionConstraint

     def initialize(version)
        @version = version
     end

     def matches?(request)
        request.headers.fetch(:accept).include?("version=#{@version}")
     rescue KeyError
        false
     end
   end
end

why isn't the request finding the route?

Upvotes: 1

Views: 3414

Answers (1)

NM Pennypacker
NM Pennypacker

Reputation: 6942

Something is likely failing in ApiVersionConstraint. To troubleshoot you can do something like:

 def matches?(request)
    byebug
    request.headers.fetch(:accept).include?("version=#{@version}")
 rescue KeyError
    false
 end

Guessing it's a problem with how you're targeting the header, so something like this might work:

request&.headers&.fetch("Accept")&.include?("version=#{@version}")

Because you have a rescue clause, you'll never get the full error; only false, so you might try removing that and seeing if you get a more descriptive error.

Upvotes: 1

Related Questions