简体   繁体   中英

REST API Design with unidirectional relationships

I am trying to build a REST API and am kind of at a loss as how to represent a many to 1 unidirectional relationships.

I have a 4 components that represents the 4 parts of a car (Engine, transmission, wheels, body).

Now obviously the component entities don't require a car entity, only the car cares about the components.

What i'm wondering is the best way to handle a REST input of the car resource.

1) Should I require a fully completed model to be submitted to the service (eg include a transmission with the full tranmission entity)?

2) Adjust the data coming in to only accept the ID of the required entity (eg engine_id, transmission_id)?

I'm a little confused on this and can't really find a good example after googling around.

public class Engine
{
    private Integer id;
    // Engine specific stuff
}

public class Transmission
{
    private Integer id;
    // Transmission specific stuff
}

public class Wheels
{
    private Integer id;
    // Wheels specific stuff
}

public class Body
{
    private Integer id;
    // Body specific stuff
}


public class Car
{
    @Id
    private Integer id;

    @ManyToOne
    @JoinColumn(name="engine_id")
    private Engine engine;

    @ManyToOne
    @JoinColumn(name="transmission_id")
    private Transmission transmission;

    @ManyToOne
    @JoinColumn(name="wheels_id")
    private Wheels wheels;

    @ManyToOne
    @JoinColumn(name="body_id")
    private Body body;
}

1) No. Cars obviously belong to your problem domain, and you should treat them as such and identify them. You should also have functionality allowing to retrieve all cars having certain engine_id and so on. According to how you state the problem, it is ambiguous if all 4 ids define a car.

2) If I understand your question correctly, yes, ids are a critical part of a REST design. This doesn't mean that you can't have functionality to display lists of subordinate objects or even searches.

Make the user first construct a valid Transmission, Engine, Body, and Wheels. Then require them to pass in either IDs or URLs to those resources when constructing the Car.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM