I was hoping someone might have some ideas on how to create a RESTful web API where models/entities are searchable by a foreign key. I see a a lot of tutorials where the functionality consist of listing all records in the entire model or retrieving a single record from the model by a primary key, but not by an arbitrary/foreign key. It my be as simple as checking for extra conditions in the request but I thought I would get some advice all the same.
1
First of all, you are going to design a very poor API if you are thinking of “foreign keys” while you design said API. As an API designer, your business is resources, not entities or keys.
If you think in terms of resources then the answer is really pretty obvious. You either have an embedded resource (orders belonging to a customer) or you have a query.
Embedded resources are just like subdirectories. You use the path for that:
/api/customers/4/orders
And a query is, not surprisingly, a query string:
/api/orders?customerId=4
Or, some people feel that this is more RESTful:
/api/orders?customer=/api/customers/4
All of these are fine. It’s partly a matter of preference and partly a matter of just how complex your relationships are.
But one thing is for sure, you’re on the wrong track talking about things primary keys and foreign keys. Those are database terms and APIs have nothing to do with your database. It’s not uncommon at all to have multiple representations of the same resource, for example:
/api/customers/123/
/api/customers/acme+inc/
/api/customers/123-acme+inc/
/api/customers/123/acme+inc/
/api/customers/me/ (say you are ACME Inc.)
The whole idea of a REST API is that these resources identifiers (URIs) are opaque. You don’t know what the “primary key” is, and you might not be entirely sure what the “ID” is. So again, just repeating one more time for the record, don’t use database terminology when you’re reasoning about a Web API, it will lead you to the wrong design.
2