Package: instant-api
instant_apiInstantly create an HTTP API with automatic type conversions, JSON RPC, and a Swagger UI. All the boring stuff is done for you, so you can focus on the interesting logic while having an awesome API. Just add methods!InstallationBasic usageTalking to the API with instant_clientUsing method paths instead of JSON-RPCHTTP status codesGlobal API configurationHandling errorsAttaching methodsCustomising method paths in the Swagger UISetting attributes directlySetting summary and description via the docstringCustomising global request and method handlingAuthenticationDependenciesWhy use this library?Installationpip install instant-apiOr to also install the corresponding Python client:pip install 'instant-api[client]'Basic usageJust write some Python functions or methods and decorate them. Parameters and the return value need type annotations so that they can be converted to and from JSON for you. You can use dataclasses for complex values.fromdataclassesimportdataclassfromflaskimportFlaskfrominstant_apiimportInstantAPIapp=Flask(__name__)@dataclassclassPoint:x:inty:int@InstantAPI(app)classMethods:deftranslate(self,p:Point,dx:int,dy:int)->Point:"""Move a point by dx and dy."""returnPoint(p.x+dx,p.y+dy)defscale(self,p:Point,factor:int)->Point:"""Scale a point away from the origin by factor."""returnPoint(p.x*factor,p.y*factor)if__name__=='__main__':app.run()Visithttp://127.0.0.1:5000/apidocs/for a complete Swagger GUI to try out the API interactively:Talking to the API withinstant_clientIf you need a Python client, I highly recommend the companion libraryinstant_client. It handles data conversion on the client side and works well with developer tools. Basic usage looks like:fromserverimportMethods,Point# the classes we defined abovefrominstant_clientimportInstantClient# The type hint is a lie, but your linter/IDE doesn't know that!methods:Methods=InstantClient("http://127.0.0.1:5000/api/",Methods()).methodsassertmethods.scale(Point(1,2),factor=3)==Point(3,6)That looks a lot like it just calledMethods.scale()directly, which is the point (no pun intended), but under the hood it did in fact send an HTTP request to the server.Using method paths instead of JSON-RPCThe API is automatically available in two flavours, and clients can choose which way they prefer to communicate:The central JSON-RPC endpoint, which follows the JSON-RPC protocol spec exactly, and is easiest to use with standard client libraries.Method paths, which make it slightly easier for humans to write requests manually (especially in the Swagger GUI) and use the features of HTTP more.To make a request to a method path, include the method name at the end of the URL, and just send the parameters object in the JSON body. Here's what such a call looks like:importrequestsresponse=requests.post('http://127.0.0.1:5000/api/scale',json={'p':{'x':1,'y':2},'factor':3,},)assertresponse.json()['result']=={'x':3,'y':6}The response will be a complete JSON-RPC response as if you had made a full JSON-RPC request. In particular it will either have aresultor anerrorkey.HTTP status codesThe central JSON-RPC endpoint will always (unless a request is not authenticated,see below) return the code HTTP status code 200 (OK), even if there's an error, as standard clients expect that.Since the method paths are not quite JSON-RPC, they may return a different code in case of errors. In particular an invalid request will lead to a 400 and an unhandled error inside a method will cause a 500.If youraise anInstantErrorinside a method, you can give it anhttp_code, e.g.raise InstantError(..., http_code=404). This will become the HTTP status codeonly if the method was called by the method path, not the JSON-RPC endpoint.Global API configurationTheInstantAPIclass requires a Flask app and has the following optional keyword-only parameters:pathis a string (default'/api/') which is the endpoint that will be added to the app for the JSON RPC. There will also be a path for each method based on the function name, e.g./api/scaleand/api/translate- seeUsing method paths instead of JSON-RPC. Specify a different string to change all of these paths.swagger_kwargsis a dictionary (default empty) of keyword arguments to pass to theflasgger.Swaggerconstructor that is called with the app. For example, you can customise the Swagger UI bypassing a dictionary toconfig:api=InstantAPI(app,swagger_kwargs={"config":{"specs_route":"/my_apidocs/",...}})Handling errorsWhen the server encounters an error, the response will contain anerrorkey (instead of aresult) with an object containingcode,data, andmessage. For example, if a method is given invalid parameters, the details of the error (either aTypeErroror a marshmallowValidationError) will be included in the response. The error code will be-32602. The response JSON looks like this:{"error":{"code":-32602,"data":{"p":{"y":["Not a valid integer."]}},"message":"marshmallow.exceptions.ValidationError: {'p': {'y': ['Not a valid integer.']}}"},"id":0,"jsonrpc":"2.0"}You can find more details, including the standard error codes for some typical errors, in theJSON-RPC protocol spec.To return your own custom error information, raise anInstantErrorin your method, e.g:frominstant_apiimportInstantAPI,InstantError@InstantAPI(app)classMethods:deffind_thing(self,thing_id:int)->Thing:...raiseInstantError(code=123,message="Thing not found anywhere at all",data=["not here","or here"],)The response will then be:{"error":{"code":123,"data":["not here","or here"],"message":"Thing not found anywhere at all"},"id":0,"jsonrpc":"2.0"}The HTTP status code depends on which flavour of the API you use - seethis section.Attaching methodsInstances ofInstantAPIcan be called with functions, classes, or arbitrary objects to add methods to the API. For functions and classes, the instance can be used as a decorator to call it.Decorating a single function adds it as an API method, as you'd expect. The function itself should not be a method of a class, since there is no way to provide the first argumentself.CallingInstantAPIwith an object will search through all its attributes and add to the API all functions (including bound methods) whose name doesn't start with an underscore (_).Decorating a class will construct an instance of the class without arguments and then call the resulting object as described above. This means it will add bound methods, so theselfargument is ignored.So givenapi = InstantAPI(app), all of these are equivalent:@apideffoo(bar:Bar)->Spam:...api(foo)@apiclassMethods:deffoo(self,bar:Bar)->Spam:...api(Methods)api(Methods())If a function is missing a type annotation for any of its parameters or for the return value, an exception will be raised. If you don't want a method to be added to the API, prefix its name with an underscore, e.g.def _foo(...).Customising method paths in the Swagger UISetting attributes directlyFor each method, aflasgger.SwaggerViewwill be created.
You can customise the view by passing a dictionary of class attributes
in the argumentswagger_view_attrsof the decorator.
For example:@api(swagger_view_attrs={"tags":["Stuff"]})deffoo(...)This will putfooin theStuffsection of the Swagger UI.Note that the below is invalid syntaxbefore Python 3.9:@InstantAPI(app)(swagger_view_attrs={"tags":["Stuff"]})deffoo(...)Setting summary and description via the docstringIf a method has a docstring, its first line will be thesummaryin the OpenAPI spec of the method path, visible in the overview in the Swagger UI.
The remaining lines will become thedescription,
visible when the path is expanded in the UI.Customising global request and method handlingTo directly control how requests are handled, create a subclass ofInstantAPIand override one of these methods:handle_request(self, method)is the entrypoint which converts a raw flask request to a response. Ifmethodis None, the request was made to the generic JSON-RPC path. Otherwisemethodis a string with the method name at the end of the request path.call_method(self, func, *args, **kwargs)calls the API methodfuncwith the given arguments. The arguments here are not yet deserialized according to the function type annotations.Unless you're doing something very weird, remember to call the parent method withsuper()somewhere.AuthenticationTo require authentication for requests:Create a subclass ofInstantAPI.Override the methoddef is_authenticated(self):.Return a boolean:Trueif a user should have access (based on the global Flaskrequestobject),Falseif they should be denied.Use an instance of your subclass to decorate methods.Unauthenticated requests will receive a 403 response with a non-JSON body.Dependenciesdatafunctions(which in turn usesmarshmallow) is used by bothinstant_apiandinstant_clientto transparently handle conversion between JSON and Python classes on both ends.Flasggerprovides the Swagger UI.json-rpchandles the protocol.Because other libraries do so much of the work,instant_apiitself is a very small library, essentially contained inone little file. You can probably read the source code pretty easily and adapt it to your needs.Why use this library?This library takes obvious inspiration fromFastAPI. So why did I write this, and why might you want to use it?It's really great withinstant_client, which lets you feel like you're calling methods locally (and your IDE helps you as if you are) even though they're executed remotely.It's easier to set up, as you don't have to specify paths or HTTP methods. If you group everything into a class, you just have to decorate the whole thing once. It's almost the minimum amount of boilerplate possible.JSON-RPC is pretty cool.It's a popular, standard protocol that has client libraries written in many languages.It lets you do bulk requests: send an array of requests, get an array of responses back.It supports notifications for when you don't care about the result.It's great when you want to work with Flask (e.g. to use other Flask libraries), or more generally if you want a WSGI application without having to embed it inside FastAPI.When my use case for this popped up, I considered FastAPI, but being able to use Flask (specifically Plotly Dash) was a hard requirement. The API was only a small part of a larger project, so I didn't want FastAPI to be 'in charge'.I tried looking through the source code of FastAPI to extract the bits I needed, like generating the Swagger spec from type annotations, but the code is very complicated and this wasn't worth it. So I wrote my own version where the dependencies do the hard work like that in a nice modular manner. What's left is a small, readable library that largely just wires other stuff together. This way if someone else is in the same situation as me where they have slightly different needs, it's now feasible for them to adapt the source code.