0

I'm building a REST API. I don't want to have real folders in my directory structure, but I'm not quite sure what to use else. My REST API uses paths like this:

api.server.com/<object>/<action>[/]

Here, <object> is the object the action <action> should be performed on. For example, a URL api.server.com/user/create would create a new user.

For now, I've come up with this:

  • The objects all have their own file, like user.php for the object /user/. In the GET variable action a string determining the action is stored.
  • I'm using a .htaccess rewrite script to rewrite the fake directories to these internal paths:

    RewriteEngine On
    RewriteRule ^(.*?)/(.*?)/?$ $1.php?action=$2 [NC,L]
    

However, I'm not sure if this is the best way of setting up a REST API. Would there be any obvious problems I'm missing here?

How does the internal file tree of a REST API usually look, or can't that be reasonably said? What are the pros and cons of different approaches?

2

I think you are pretty much on the right track... It is hard to say if any particular way of structuring folders as "the best", but I can share what I have seen. In particular, the way ASP.NET MVC structures this sort of thing is as follows:

  • Models
  • Views
  • Controllers
  • {Miscellaneous other folders}

Models Contains the classes that represent your view models, or in the case of an API project, the data types that your API sends and receives; eg Person { Name, Rank, SerialNumber }.

Views Contains the files which generate your views; for an API project you don't really have views, you would just use some sort of JSON or XML serialization layer, so you probably don't need something like this.

Controllers Contains the classes that have your actions on them. This is pretty much what you are talking about doing, but it is worth nothing the separation between the data class (ie the Person object, with { Name, Rank, SerialNumber }) and the Person controller, which supports GET, PUT, POST, DELETE of a Person object.

Miscellaneous other folders would contain any other resources you need; also not all that necessary for a purely API project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.