ServiceStack JsonServiceClient URLs - servicestack

I'm evaluating ServiceStack JsonServiceClient and the requests use a generic /json/reply endpoint:
https://techstacks.io/json/reply/GetTechnology?slug=ServiceStack
Is it possible to use the endpoints declared in the services (e.g.: [Route("/hello")])?

The .NET (C#,F#,VB.NET) JsonServiceClient does use the user defined routes as they’re able to access the .NET metadata attributes, other languages can’t as they are unable the access the same runtime metadata so they’re typically emitted in comments for documentation purposes and use ServiceStack’s pre-defined routes which is enabled by default on all ServiceStack Services which allows for a simpler generic implementation that can invoke any API.
All JsonServiceClient in all languages also offer API methods which accept a string path which can be used to call APIs using your user-defined routes, e.g:
client.get<GetTechnologyResponse>("/technology/ServiceStack")
client.get<GetTechnologyResponse>("https://techstacks.io/technology/Redis")
// https://techstacks.io/technology?Slug=ServiceStack
client.get<GetTechnologyResponse>("/technology", { Slug: "ServiceStack" })
as well as POST Request DTOs to Custom URLs:
client.postToUrl("/custom-path", request, { Slug: "ServiceStack" });
client.putToUrl("http://example.org/custom-path", request);
JS lib also contain some additional APIs which can help generate populated query strings for user defined routes, e.g:
combinePaths("path","to","..","join") //= path/join
createPath("path/{foo}", {foo:1,bar:2}) //= path/1
createUrl("http://host/path/{foo}",{foo:1,bar:2}) //= http://host/path/1?bar=2

Related

How to use `fastapi_another_jwt_auth` in the middleware instead of via dependency injection in FastAPI?

I have a FastAPI project which uses fastapi_another_jwt_auth as a way of authenticating users. I'd intend to implement it in most of my endpoints except for a few whitelisted ones, but I find it hard to unit test endpoints that require authentication so I'm thinking of implementing it in a middleware with a simple if-else check for whitelisted endpoints. This way, I just need to disable the middleware to run unit tests and testing for authentication becomes trivial since we're just testing against a whitelist.
The API for fastapi_another_jwt_auth seems designed around the concept of Dependency Injection for FastAPI. Is there a way to use the same library in the middleware?
I looked at the code for fastapi_another_jwt_auth. Apparently, when injecting, the framework runs the AuthJWT constructor, which takes in the Request and Response object. This is shown below.
class AuthJWT(AuthConfig):
def __init__(self,req: Request = None, res: Response = None):
...
Once it is successfully initialised, we can then use the .jwt_required() method.
So the way to implement it in the middleware is:
#app.middleware("http")
async def middleware_callback(req, call_next):
if not whitelisted: # this is pseudocode
auth = AuthJWT(req)
auth.jwt_required() # throws error when user is not authenticated
# rest of the logic
...
This way, I can manage all authentication at the middleware level and I don't have to inject the AuthJWT object into my view functions.

How to Convert url requests to Dtos in ServiceStack Typescript Client

Is it possible to convert urls into Dtos in the Service Stack typescript json client? I see these extensions on the c# client but not in typescript
ServiceStack's TypeScript Request DTOs don't have access to the [Route] attribute metadata so they only generate pre-defined URLs within the Service Client but you can use the createUrl helper to be able to generate a URL by passing in the route definition, e.g:
import { createUrl } from '#servicestack/client';
let url = createUrl('/hello/{Name}', { name, foo:1 });
Which will generate that populates the route path and appends any additional object args to the queryString, e.g:
/hello/name?foo=1

Allowing multiple routes for a single Backbone Model

I am fairly new to Backbone and am creating some basic API for a site. However, I came across a problem that I have yet to find a solution to.
On my front end I have a Backbone Model called Item that has a urlRoot: "/item". Now this urlRoot is used by Backbone to send different HTTP requests to the server correct? So if my backbone model uses Item.fetch() it will send a GET request, and a Item.save() may send a POST request.
My backend then has a bunch of listener functions to handle different cases like "/createItem", "/updateItem", "deleteItem", ect. Can all of these be handled using the basic urlRoot that is provided? Or do I have to specific what route to emit explicitly?
If you want to follow the default way of doing it, your backend should not use different names for each of the CRUD operations. It should use the url you specified using rootUrl + /id of the model, and should handle an HTTP POST, GET, PUT, or, DELETE for that single URL (with the exception that the POST URL has no /id attached).
See: http://backbonejs.org/#Sync
Since you are using an unconventional set of rest endpoints you will need to provide a custom sync method for your model:
sync : function(method, model, options) {
if (method === 'read') {
this.baseUrl = '/item';
return Backbone.sync.apply(this, arguments);
} ...
}

ServiceStack ServiceClient HTTP 206 and Range header

I'm using ServiceStack ServiceClient to write an API wrapper. The API returns HTTP 206 if the number of entities to be returned is too great. Is there a a good way to handle this with ServiceClient, for example for an API endpont that's wrapped like this:
var result = client.Get<IEnumerable<TResource>>("path");
Is this a ServiceStack service that's returning a HTTP 206? as this isn't behavior that's in-built into ServiceStack. If you are using a ServiceStack you may need to increase your IIS/ASP.NET Request limits to allow larger responses.
Otherwise if you're talking to a 3rd Party API, you shouldn't use ServiceStack's Service Clients which are opinionated towards consuming ServiceStack services. You should instead use something like the HTTP Utils built into ServiceStack which would allow you to specify custom HTTP Headers if your service supports it, you can ask for a Partial Content-Range by specifying it in a HTTP Request Filter, e.g:
var json = "http://example.org/users".GetJsonFromUrl(
requestFilter: httpReq => httpReq.AddRange(0, 1000));

Get HttpResult using the JsonServiceClient

I am returning HttpResult from one of the rest service methods using servicestack's new API. Is there a way to get the HttpResult using the JsonServiceClient?
For ex: JSonServiceClient.Send<HttpResult>("DELETE","person", new { PersonID = 30 });
I want to inspect the header information from the httpresult.
Thanks.
There's no such thing as a HttpResult client response from a ServiceStack web service.
You use a HttpResult to customize the HTTP Response that's returned from your service, e.g. Add additional HTTP Headers. But the response body the client sees is still only the Response DTO (if any).
Use fiddler, wireshark, chome web inspector (if this is an Ajax call) or something like ServiceStack's Request Logger plugin to inspect the HTTP traffic.
Invalid use of ServiceStack's REST Clients
Also consider using the appropriate Clients REST API like client.Delete(), client.Get() etc instead of overloading the T.Send() method (which is usually a POST).
Use Typed DTOs in the ServiceClient instead of anonymous types which are not supported.
Inspecting HTTP Headers using the ServiceStack Service Clients
ServiceStack's Service Clients provide Local and Global WebResponse (and Request) filters that you can use to introspect the WebClient's HttpWebResponse returned for that request, e.g:
client.ResponseFilter = httpRes => {
httpRes.Headers.. //do something with returned headers
};
client.Delete(new Person { Id = 30, ...});

Resources