c#, web api, swashbuckler/swagger - rest

This is my first web api, first web app, and first time Ive used swagger via swashbuckler.
I'm using TPH for my equipment db table.
For example, I have base class called equipment with several child classes inherited from equipment. (This isnt real code so Ive not put in all the publics etc)
As I sorta expect, the model description when I run swagger in my browser, just returns the model for the equipment class
I've googled how to show all possible models but can't understand the replies as they don't relate to c#, or api controllers using comments for documentation, or they're written for people who understand this more than I do.
is anybody able to post an example, or point me to a beginner tutorial please, on how to get swagger display all possible models. I've had to write several different api calls to get around this, just so the models are shown.
thanks
class equipment
{
public int id{get;set;}
public int foo{get;set;}
public int bar{get;set;}
}
class bucket : equipment
{
public int booboo{get;set;}
}
class mop : equipment
{
public int lala{get;set;}
}
// equipmentcontroller class get function
/// <summary>
/// Returns a piece of equipment.<br/>
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Route(#"{id:int}"), ResponseType(typeof(equipment))]
public IHttpActionResult GetMop(int id)
{
return result != null ? (IHttpActionResult)Ok(GetMop[id]) : NotFound();
}

What you're suggesting isn't possible. In Swagger, the definition of responses for an operation is basically a mapping of different HTTP status codes to specific response objects. (Have a look at http://swagger.io/specification/#responsesObject)
It's not going to be possible for you to represent that a 200 OK for an operation could either return a response representing a mop or a response representing a bucket.
You mention "I've had to write several different api calls to get around this, just so the models are shown.", this is what I'd expect from a RESTful API. Different kinds of resources are handled by different endpoints.

Related

In a REST API client, do you need multiple GET methods for every endpoint?

I have been trying to learn a bit about api clients.
You have an api at www.expamle.com/api and you need to be able to GET all users at www.expamle.com/api/users and also get them by id at www.example.com/api/users/{id} .
In your code do you need to have a separate function to get ALL records and only one record?
What I don't get is how to properly serialize the results since when you get multiple records it returns you an array but it doesn't work with a single record.
Also, would you need more GET functions for other endpoints such as http://www.example.com/api/products/
Yes,you typically implement the two separate calls with two methods like this (C#):
[Route("users")]
public class UsersController : Controller
{
// users resource: /api/users/
[Route("")]
[HttpGet]
public IActionResult GetUsers() { ... }
// single user resource: /api/users/5
[Route("{id:long}")]
[HttpGet]
public IActionResult GetUser(long id) { ... }
}
This way you can explicitly define your two different routes. You you will find it also easier to deal with the different requests: less code, simpler to read etc. Avoid code redundancy though.
The serialization depends on what you require. There are multiple options. I personally stick to JSON these days. As a human I can read the data easily, yet the package sizes are fairly small compared to SOAP or any custom XML. Dealing with JSON is simple, especially in ASP.NET Core. You just return an IEnumerable<...> and the framework takes care of everything else:
[Route("")]
[HttpGet]
public IActionResult GetUsers()
{
return Ok(
new List<Users>
{
new User(1, ...),
new User(2, ...),
new User(3, ...)
});
}
For other resources, e. g. your products resource, use other controllers. I personally follow the RESTful guidance: Wikipedia and Microsoft Docs.

How to Route non-CRUD actions in a RESTful ASP.NET Web API?

I am trying to design a RESTful web API for our service using ASP.NET Web API. I'm running into trouble with figuring out how to route non-CRUD actions to the proper controller action. Let's assume my resource is a door. I can do all of the familiar CRUD things with my door. Let's say that model for my door is:
public class Door
{
public long Id { get; set; }
public string InsideRoomName { get; set; }
public string OutsideRoomName { get; set; }
}
I can do all of my standard CRUD operations via my web api:
POST: http://api.contoso.com/v1/doors
GET: http://api.contoso.com/v1/doors
GET: http://api.contoso.com/v1/doors/1234
GET: http://api.contoso.com/v1/doors?InsideRoomName=Cafeteria
PUT: http://api.contoso.com/v1/doors/1234
DELETE: http://api.contoso.com/v1/doors/1234
and so on. Where I run into trouble is when I need to model the non-CRUD actions against my door. I want to model a Lock and Unlock verb against my resource. Reading through the ASP.NET articles the guidance seems to be to switch to an RPC style call when using custom actions. This gives me a path:
PUT: http://api.contoso.com/v1/doors/1234/lock
PUT: http://api.contoso.com/v1/doors/1234/unlock
This seems to conflict with the spirit of REST which aims for the path to indicate a resource. I suppose I could model the verb as a resource:
POST: http://api.contoso.com/v1/doors/1234/lockrequests
POST: http://api.contoso.com/v1/doors/1234/unlockrequests
In this case I could still use the recommend {controller}/{id}/{action} but it seems like I'm still creating a mixed RPC / REST API. Is it possible, or even recommended as far as REST interfaces go, to put the custom action in the list of parameters?
PUT: http://api.contoso.com/v1/doors/1234?lock
PUT: http://api.contoso.com/v1/doors/1234?unlock
I could foresee a need to have this call supported with query parameters as well, such as:
PUT: http://api.contoso.com/v1/doors?lock&InsideRoomName=Cafeteria
How would I create the route to map this request to my DoorsController?
public class DoorsController : ApiController
{
public IEnumerable<Doord> Get();
public Door Get(long id);
public void Put(long id, Door door);
public void Post(Door door);
public void Delete(long id);
public void Lock(long id);
public void Unlock(long id);
public void Lock(string InsideRoomName);
}
I may be making some false assumptions here regarding what is and is not best practices with respect to REST API design, so any guidance there is appreciated as well.
From RESTful principle, maybe it's best to introduce a 'status' property to manage those non-CURD actions. But I don't think it meets the real production development.
Every answer to this kind of question, looks like you must have to use a work-around to enforce your API design meets RESTful. But my concern is, is that really making convenience to both user and developer?
let's take a look on the API3.0 design of Google bloger: https://developers.google.com/blogger/docs/3.0/reference, it's using lot URL for non-CURD actions.
And this is interesting,
POST /blogs/blogId/posts/postId/comments/commentId/spam
and the description is
Marks a comment as spam. This will set the status of the comment to spam, and hide it in the default comment rendering.
You can see, a comment has a status to indicate whether it's a spam or not, but it was not designed like the answer mentioned above by JoannaTurban.
I think from user point of view, it's more convenient. Don't need to care the structure and the enum value of the "status". And actually you can put lot of attributes into the definition of "status", like "isItSpam", "isItReplied", "isItPublic" etc. The design will becomes unfriendly if the status has many things.
On some business logic requirement, to use an easy to understand verb, instead of trying to make it completely a "real" RESTful, it's more productive, for both user and developer. This is my opinion.
To handle the lock/unlock scenario you could consider adding a State property to the Door object:
public State State { get; set; }
where State is an enum of available values, e.g.
{
LockedFromOutsideRoom,
LockedFromInsideRoom,
Open
}
To clarify: That you're adding a state to the object is not against restful principles as the state is passed over the api every time you make a call to do something with the Door.
Then via the api you would send a PUT/POST request to change the state of the Door on each lock/unlock. Post would probably be better as it's only one property that gets updated:
POST: http://api.contoso.com/v1/doors/1234/state
body: {"State":"LockedFromInsideRoom"}
From a REST perspective you probably want to be treating the lock as a resource in and of itself. This way you create and delete the lock independently of the door (although presumably locate the lock endpoint from the door representation). The URL of the resource is probably going to be related to the URL of the door, however from a RESTful perspective this is irrelevant. REST is about relationships between resources, so the important part is that the url of the lock is discoverable from the representation of the door.

Dependency Injection/Property Injection on an asp.NET MVC 2 ActionFilter: Help!

I've been trying to wrap my head around the topics posted at this similar question:
Is it possible to use Dependency Injection/IoC on an ASP.NET MVC FilterAttribute?
However, I'm just not getting anywhere. Not to mention, all the solutions appear to have dependencies on other libraries which I'm not able to use (MvcContrib, Unity).
Can anyone toss together some code to explain how to make this property injection work? Or if there is another way to make this happen?
Thanks much!
Relevant code 1: Controller
namespace TxRP.Controllers
{
[GetMasterPageData]
public class BaseController : Controller
{
}
}
Relevant code 2: ActionFilter
public class GetMasterPageData : ActionFilterAttribute
{
private IEmployee emp; //<--Need to inject!
private ICache cache; //<--Need to inject!
/// <summary>
/// ActionFilter attribute which inserts the user name, access level and any error/warning messages to the MasterPage
/// Session variables which are consumed primarily by the LogOnUserControl.
/// The MasterPage will display any warning or error messages.
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Code
}
It's not possible to use DI with attributes because they are statically compiled into your classes, so nothing can ever be injected. Some people may tell you that you can use a sort of static factory to get your dependencies, but that's not Dependency Injection - that would be Service Location - which is an anti-pattern.
However, it's possible to combine DI with action filters if you abandon the idea of attributes, but not particularly easy. You'll need to create a custom IActionInvoker, although the easiest way to do that is to derive from ControllerActionInvoker and override its GetFilters method. Here's a blog post that explains how to do that for error handling - you should be able to extrapolate from that.
When you get tired of doing that I'd advice you to switch to composing cross-cutting concerns out of Decorators and other design patterns. In that way you can implement your cross-cutting concerns independently of constraining technology.

DDD, handling dependencies

Boring intro:
I know - DDD isn't about technology. As i see it - DDD is all about creating ubiquitous language with product owner and reflecting it into code in such a simple and structured manner, that it just can't be misinterpreted or lost.
But here comes a paradox into play - in order to get rid of technical side of application in domain model, it gets kind a technical - at least from design perspective.
Last time i tried to follow DDD - it ended up with whole logic outside of domain objects into 'magic' services all around and anemic domain model.
I've learnt some new ninja tricks and wondering if I could handle Goliath this time.
Problem:
class store : aggregateRoot {
products;
addProduct(product){
if (new FreshSpecification.IsSatisfiedBy(product))
products.add(product);
}
}
class product : entity {
productType;
date producedOn;
}
class productTypeValidityTerm : aggregateRoot {
productType;
days;
}
FreshSpecification is supposed to specify if product does not smell. In order to do that - it should check type of product, find by it days how long product is fresh and compare it with producedOn. Kind a simple.
But here comes problem - productTypeValidityTerm and productType are supposed to be managed by client. He should be able to freely add/modify those. Because I can't traverse from product to productTypeValidityTerm directly, i need to somehow query them by productType.
Previously - i would create something like ProductService that receives necessary repositories through constructor, queries terms, performs some additional voodoo and returns boolean (taking relevant logic further away from object itself and scattering it who knows where).
I thought that it might be acceptable to do something like this:
addProduct(product, productTypeValidityTermRepository){...}
But then again - i couldn't compose specification from multiple specifications underneath freely what's one of their main advantages.
So - the question is, where to do that? How store can be aware of terms?
With the risk of oversimplifying things: why not make the fact whether a Product is fresh something a product "knows"? A Store (or any other kind of related object) should not have to know how to determine whether a product is still fresh; in other words, the fact that something like freshSpecification or productTypeValidityTerm even exist should not be known to Store, it should simply check Product.IsFresh (or possibly some other name that aligns better with the real world, like ShouldbeSoldBy, ExpiresAfter, etc.). The product could then be aware how to actually retrieve the protductTypeValidityTerm by injecting the repository dependency.
It sounds to me like you are externalizing behavior which should be intrinsic to your domain aggregates/entities, eventually leading (again) to an anemic domain model.
Of course, in a more complicated scenario, where freshness depends on context (e.g., what's acceptable in a budget store is not deemed worthy for sale at a premium outlet) you'd need to externalize the entire behavior, both from product and from store, and create a different type altogether to model this particular behavior.
Added after comment
Something along these lines for the simple scenario I mentioned: make the FreshSpec part of the Product aggregate, which allows the ProductRepository (constructor-injected here) to (lazy) load it when needed.
public class Product {
public ProductType ProductType { get; set; }
public DateTime ProducedOn { get; set; }
private FreshSpecification FreshSpecification { get; set; }
public Product(IProductRepository productRepository) { }
public bool IsFresh() {
return FreshSpecification
.IsSatisfiedBy(ProductType, ProducedOn);
}
}
The store doesn't know about these internals: all it cares about is whether or not the product is fresh:
public class Store {
private List<Product> Products = new List<Product>();
public void AddProduct(Product product) {
if (product.IsFresh()) {
Products.Add(product);
}
}
}

What is the value of Interfaces?

Sorry to ask sich a generic question, but I've been studying these and, outside of say the head programming conveying what member MUST be in a class, I just don't see any benefits.
There are two (basic) parts to object oriented programming that give newcomers trouble; the first is inheritance and the second is composition. These are the toughest to 'get'; and once you understand those everything else is just that much easier.
What you're referring to is composition - e.g., what does a class do? If you go the inheritance route, it derives from an abstract class (say Dog IS A Animal) . If you use composition, then you are instituting a contract (A Car HAS A Driver/Loan/Insurance). Anyone that implements your interface must implement the methods of that interface.
This allows for loose coupling; and doesn't tie you down into the inheritance model where it doesn't fit.
Where inheritance fits, use it; but if the relationship between two classes is contractual in nature, or HAS-A vs. IS-A, then use an interface to model that part.
Why Use Interfaces?
For a practical example, let's jump into a business application. If you have a repository; you'll want to make the layer above your repository those of interfaces. That way if you have to change anything in the way the respository works, you won't affect anything since they all obey the same contracts.
Here's our repository:
public interface IUserRepository
{
public void Save();
public void Delete(int id);
public bool Create(User user);
public User GetUserById(int id);
}
Now, I can implement that Repository in a class:
public class UserRepository : IRepository
{
public void Save()
{
//Implement
}
public void Delete(int id)
{
//Implement
}
public bool Create(User user)
{
//Implement
}
public User GetUserById(int id)
{
//Implement
}
}
This separates the Interface from what is calling it. I could change this Class from Linq-To-SQL to inline SQL or Stored procedures, and as long as I implemented the IUserRepository interface, no one would be the wiser; and best of all, there are no classes that derive from my class that could potentially be pissed about my change.
Inheritance and Composition: Best Friends
Inheritance and Composition are meant to tackle different problems. Use each where it fits, and there are entire subsets of problems where you use both.
I was going to leave George to point out that you can now consume the interface rather than the concrete class. It seems like everyone here understands what interfaces are and how to define them, but most have failed to explain the key point of them in a way a student will easily grasp - and something that most courses fail to point out instead leaving you to either grasp at straws or figure it out for yourself so I'll attempt to spell it out in a way that doesn't require either. So hopefully you won't be left thinking "so what, it still seems like a waste of time/effort/code."
public interface ICar
{
public bool EngineIsRunning{ get; }
public void StartEngine();
public void StopEngine();
public int NumberOfWheels{ get; }
public void Drive(string direction);
}
public class SportsCar : ICar
{
public SportsCar
{
Console.WriteLine("New sports car ready for action!");
}
public bool EngineIsRunning{ get; protected set; }
public void StartEngine()
{
if(!EngineIsRunning)
{
EngineIsRunning = true;
Console.WriteLine("Engine is started.");
}
else
Console.WriteLine("Engine is already running.");
}
public void StopEngine()
{
if(EngineIsRunning)
{
EngineIsRunning = false;
Console.WriteLine("Engine is stopped.");
}
else
Console.WriteLine("Engine is already stopped.");
}
public int NumberOfWheels
{
get
{
return 4;
}
}
public void Drive(string direction)
{
if (EngineIsRunning)
Console.WriteLine("Driving {0}", direction);
else
Console.WriteLine("You can only drive when the engine is running.");
}
}
public class CarFactory
{
public ICar BuildCar(string car)
{
switch case(car)
case "SportsCar" :
return Activator.CreateInstance("SportsCar");
default :
/* Return some other concrete class that implements ICar */
}
}
public class Program
{
/* Your car type would be defined in your app.config or some other
* mechanism that is application agnostic - perhaps by implicit
* reference of an existing DLL or something else. My point is that
* while I've hard coded the CarType as "SportsCar" in this example,
* in a real world application, the CarType would not be known at
* design time - only at runtime. */
string CarType = "SportsCar";
/* Now we tell the CarFactory to build us a car of whatever type we
* found from our outside configuration */
ICar car = CarFactory.BuildCar(CarType);
/* And without knowing what type of car it was, we work to the
* interface. The CarFactory could have returned any type of car,
* our application doesn't care. We know that any class returned
* from the CarFactory has the StartEngine(), StopEngine() and Drive()
* methods as well as the NumberOfWheels and EngineIsRunning
* properties. */
if (car != null)
{
car.StartEngine();
Console.WriteLine("Engine is running: {0}", car.EngineIsRunning);
if (car.EngineIsRunning)
{
car.Drive("Forward");
car.StopEngine();
}
}
}
As you can see, we could define any type of car, and as long as that car implements the interface ICar, it will have the predefined properties and methods that we can call from our main application. We don't need to know what type of car is - or even the type of class that was returned from the CarFactory.BuildCar() method. It could return an instance of type "DragRacer" for all we care, all we need to know is that DragRacer implements ICar and we can carry on life as normal.
In a real world application, imagine instead IDataStore where our concrete data store classes provide access to a data store on disk, or on the network, some database, thumb drive, we don't care what - all we would care is that the concrete class that is returned from our class factory implements the interface IDataStore and we can call the methods and properties without needing to know about the underlying architecture of the class.
Another real world implication (for .NET at least) is that if the person who coded the sports car class makes changes to the library that contains the sports car implementation and recompiles, and you've made a hard reference to their library you will need to recompile - whereas if you've coded your application against ICar, you can just replace the DLL with their new version and you can carry on as normal.
So that a given class can inherit from multiple sources, while still only inheriting from a single parent class.
Some programming languages (C++ is the classic example) allow a class to inherit from multiple classes; in this case, interfaces aren't needed (and, generally speaking, don't exist.)
However, when you end up in a language like Java or C# where multiple-inheritance isn't allowed, you need a different mechanism to allow a class to inherit from multiple sources - that is, to represent more than one "is-a" relationships. Enter Interfaces.
So, it lets you define, quite literally, interfaces - a class implementing a given interface will implement a given set of methods, without having to specify anything about how those methods are actually written.
Maybe this resource is helpful: When to Use Interfaces
It allows you to separate the implementation from the definition.
For instance I can define one interface that one section of my code is coded against - as far as it is concerned it is calling members on the interface. Then I can swap implementations in and out as I wish - if I want to create a fake version of the database access component then I can.
Interfaces are the basic building blocks of software components
In Java, interfaces allow you to refer any class that implements the interface. This is similar to subclassing however there are times when you want to refer to classes from completely different hierarchies as if they are the same type.
Speaking from a Java standpoint, you can create an interface, telling any classes that implement said interface, that "you MUST implement these methods" but you don't introduce another class into the hierarchy.
This is desireable because you may want to guarantee that certain mechanisms exist when you want objects of different bases to have the same code semantics (ie same methods that are coded as appropriate in each class) for some purpose, but you don't want to create an abstract class, which would limit you in that now you can't inherit another class.
just a thought... i only tinker with Java. I'm no expert.
Please see my thoughts below. 2 different devices need to receive messages from our computer. one resides across the internet and uses http as a transport protocol. the other sits 10 feet away, connect via USB.
Note, this syntax is pseudo-code.
interface writeable
{
void open();
void write();
void close();
}
class A : HTTP_CONNECTION implements writeable
{
//here, opening means opening an HTTP connection.
//maybe writing means to assemble our message for a specific protocol on top of
//HTTP
//maybe closing means to terminate the connection
}
class B : USB_DEVICE implements writeable
{
//open means open a serial connection
//write means write the same message as above, for a different protocol and device
//close means to release USB object gracefully.
}
Interfaces create a layer insulation between a consumer and a supplier. This layer of insulation can be used for different things. But overall, if used correctly they reduce the dependency density (and the resulting complexity) in the application.
I wish to support Electron's answer as the most valid answer.
Object oriented programming facilitates the declaration of contracts.
A class declaration is the contract. The contract is a commitment from the class to provide features according to types/signatures that have been declared by the class. In the common oo languages, each class has a public and a protected contract.
Obviously, we all know that an interface is an empty unfulfilled class template that can be allowed to masquerade as a class. But why have empty unfulfilled class contracts?
An implemented class has all of its contracts spontaneously fulfilled.
An abstract class is a partially fulfilled contract.
A class spontaneously projects a personality thro its implemented features saying it is qualified for a certain job description. However, it also could project more than one personality to qualify itself for more than one job description.
But why should a class Motorcar not present its complete personality honestly rather than hide behind the curtains of multiple-personalities? That is because, a class Bicycle, Boat or Skateboard that wishes to present itself as much as a mode of Transport does not wish to implement all the complexities and constraints of a Motorcar. A boat needs to be capable of water travel which a Motorcar needs not. Then why not give a Motorcar all the features of a Boat too - of course, the response to such a proposal would be - are you kiddin?
Sometimes, we just wish to declare an unfulfilled contract without bothering with the implementation. A totally unfulfilled abstract class is simply an interface. Perhaps, an interface is akin to the blank legal forms you could buy from a stationary shop.
Therefore, in an environment that allows multiple inheritances, interfaces/totally-abstract-classes are useful when we just wish to declare unfulfilled contracts that someone else could fulfill.
In an environment that disallows multiple inheritances, having interfaces is the only way to allow an implementing class to project multiple personalities.
Consider
interface Transportation
{
takePassengers();
gotoDestination(Destination d);
}
class Motorcar implements Transportation
{
cleanWindshiedl();
getOilChange();
doMillionsOtherThings();
...
takePassengers();
gotoDestination(Destination d);
}
class Kayak implements Transportation
{
paddle();
getCarriedAcrossRapids();
...
takePassengers();
gotoDestination(Destination d);
}
An activity requiring Transportation has to be blind to the millions alternatives of transportation. Because it just wants to call
Transportation.takePassengers or
Transportation.gotoDestination
because it is requesting for transportation however it is fulfilled. This is modular thinking and programming, because we don't want to restrict ourselves to a Motorcar or Kayak for transportation. If we restricted to all the transportation we know, we would need to spend a lot of time finding out all the current transportation technologies and see if it fits into our plan of activities.
We also do not know that in the future, a new mode of transport called AntiGravityCar would be developed. And after spending so much time unnecessarily accommodating every mode of transport we possibly know, we find that our routine does not allow us to use AntiGravityCar. But with a specific contract that is blind any technology other than that it requires, not only do we not waste time considering all sorts of behaviours of various transports, but any future transport development that implements the Transport interface can simply include itself into the activity without further ado.
None of the answers yet mention the key word: substitutability. Any object which implements interface Foo may be substituted for "a thing that implements Foo" in any code that needs the latter. In many frameworks, an object must give a single answer to the question "What type of thing are you", and a single answer to "What is your type derived from"; nonetheless, it may be helpful for a type to be substitutable for many different kinds of things. Interfaces allow for that. A VolkswagonBeetleConvertible is derived from VolkswagonBeetle, and a FordMustangConvertible is derived from FordMustang. Both VolkswagonBeetleConvertible and FordMustangConvertible implement IOpenableTop, even though neither class' parent type does. Consequently, the two derived types mentioned can be substituted for "a thing which implements IOpenableTop".