Is a REST API used to build UI's? - api

So I know that an API is basically something that passes data to applications such as a person's username.
But I was wondering whether API is used to create UI and up to what extent?
So let's say my mobile application needs a login screen. When the application loads should the application send a GET request which then gives them a JSON answer of what inputs it needs for the POST request (eg: Username, Password, Agree to terms checkbox)
Sorry if my question is low quality. I'm just beginning to learn about API's

APIs may be used for everything.
It's better to say that APIs' responses are used to fill prerendered UIs with required data.
So, you create table with undefined number of fields and require JSON structure from remote API like:
{[{"username": "string", "opts": []}, {"password": "string", "opts": ["hidden"]}]},where hidden stands for hiding letters during input.
I have had some experience with that case, but the number and specification of input fields are usually known on the client side.
Your method is useful for GUI database clients and administration tools.

Related

Building an API to send random numbers to my website [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am trying to make a custom API which uploads random numbers generated to my website page (to learn how API works). And whenever I want to see the page, I use my API key to do so. Can you help me in this? I am new to API stuff.
When creating APIs, there are lots of decisions to make. You could render your structure on the client-side and query your application server via RESTful API calls. Or you could have a server-side rendering approach and use your API internally. There are four main types of APIs:
Partner
Internal
Composite
REST
https://www.techtarget.com/searchapparchitecture/tip/What-are-the-types-of-APIs-and-their-differences
In your scenario it seems that you need to either choose an internal API approach or a RESTful approach.
Your random number function itself would be similar in both cases (a simple function written in the language of your choice).
However, the token usage largely depends on the type of your API.
You need to decide whether you are going to have usernames and passwords and is the purpose of your token only to avoid frequently logging in with very sensitive data, such as username and password, so, you use a token instead, which, if falls into the wrong hands, then they could not steal the identity of your users for good, as they are still not reaching these credentials. If so, then you will need to generate the token periodically. A way to do so is to generate it every week/month (whatever) and somehow send it out to your users. Or it could be generated whenever the user has to log in, sent to the user, who will be able to use that token from there on.
Or, you could separate the token from the login and provide a UI for the user where he/she can generate tokens while being logged in. There are quite many ways to approach this.
Otherwise, if there is no username and password and, there is a token and secret to identify the user, then you will need an alternative to the login. It could be a simple request for token generation. Or it could be a repeatedly generated and sent token.
In any measures, when you intend to run an API function as a user, then you will need to send the information that identifies your user. On most webpages this is handled by getting a session ID (that acts as a token) upon login and then, while the session exists, that session ID is always sent to the webpage, whatever request is being sent, this is how the website knows that you are logged in. Most webservers and programming languages that handle web requests also handle token generation and usage and browsers are in line with these through the cookies, which are small files that contain information for the website.
If you are having a custom environment or you prefer a custom token management, then of course you can implement your own.
But, if you want to achieve simplicity, then you could implement a register and a login feature for your API as well as the number randomizer, so these are 3 API functions for now, call the register when a user registers, store a 1-way-encrypted password, do a validation (like email sending with a token to the user) and implement token-based user validation, which is a fourth API function. So, the user:
registers
receives an email with a token
clicks on a link that has that token as a request parameter
once that page opens, store the user as an authenticated user and remove the registration token
This will enable logging in for your user. Once your user is logged in, a session ID should be generated (in PHP you need to look into the functions whose name start with session_, for example) and then using that session ID your API should make sure that the randomizer can be called and your UI should be designed in such a way that this feature could be found by users.
If I may, I advise you to avoid getting into your own token generation while you are learning, choose the simplest ways and once the simplistic configuration you have chosen is working reliably, then you may choose to write your own token logic if you prefer that for some reason.

Architecturing testmode/livemode using OAuth 2 token

The title is a bit obscure. I'm interested about some feedbacks on a specific architecture pattern.
Let's take as an example the Stripe API: when you are using this API, the system is basically broken into two parts: live mode and test mode. If you hit the "/customers" end-point, you can either retrieve test mode customers or live mode customers, based on the type of API key used.
I'm asking myself how I could implement such a pattern using an OAuth 2 access token.
In my workflow, I have a single application page (JavaScript) that communicates through my API. I have a "live"/"test" switch, so basically my whole website is replicated into two distinct environments.
When I log in into my application, my authorization server creates a unique access token (OAuth 2 Bearer token), that is send for each requests. But obviously, my access token is tied to the "session", not an "environment" (live or false), so if I want to implement a switch live mode / test mode, I cannot rely on the token, because the token is "generic".
I've thought about two options:
Depending on live mode or test mode, I send an additional header to all my request (like X-Livemode which is either true or false). Then, in my back-end, I reuse this header to automatically adds a filter on all my requests.
If I switch to live mode or test mode, I ask my authorization server another access token. This would means that access token would have additional context information. However this seems a bit complicated, and I'm not sure that OAuth 2 spec allows token to have such additional information.
I'm not sure if this post is clear or not :p.
The second part of the question, is what is the best way to implement such a system where all the resources are basically duplicated between live / test mode ?
In my understand, it should be as simple as adding a "isLivemode" property to all resources, and make sure that all my SQL queries are aware of this. Is this correct?
Thanks!
A much simpler solution I've used in the past (albeit a bit of a workaround) is just to append "live" or "test" (base64 or hex encoded) to the api key, like so:
Imagine your actual key is:
9a0554259914a86fb9e7eb014e4e5d52
In your key presentation, present your key to the user as:
9a0554259914a86fb9e7eb014e4e5d526c697665
Then use a regular expression to strip off the known characters.
Alternatively, if you're equipped to handle key-value maps, a more "OAuth2-spec" approach would be to generate unique keys for live and test and do a key-value map lookup on the request to determine if one belongs to live or test.

Authorization dependent REST API

as part of a server REST API design I'm considering I'd like to be able to return data that is conditional on the level of authorization of the client. What would be the recommended way of doing accomplishing that and still calling it one API? More specifically, consider the following example for a book access API:
HTTP GET /library/books/{book-name}
Any authenticated client should be able to get (JSON) data for the book, like:
{
"book":
{"book-name":"abc", "author":"someone"}
}
But a specific sub-set of authenticated clients should also be able to get:
{
"book":
{"book-name":"abc", "author":"someone"},
"private-info" :
{"book-status":"on-loan", "price":"$20"}
}
For a given book, any suitably authorized client can also access the "private info" via a direct HTTP GET /library/books/{book-name}/private-info.
Now, assuming a suitable client authentication scheme is in place, I cannot help but think that the HTTP GET /library/books/{book-name} above is actually looking like two API's, distinguished by authorization state on the server regarding authentication. This seems not very RESTful.
Perhaps it would be better to keep the base GET book API the same for all without ever having any "private-info", while offerring authorized clients only access to the private-info URI and returning 403 to all others?
How does this type of conditional data access typically get handled with REST APIs?
There is nothing inherently wrong with your approach - it makes good sense to hide information as you suggest based on the user's authorization. REST says nothing about this - the representation of a resource may depend on user authorization, moon phase or what ever else you can think of.
You can although improve caching if you extract the private information to a separate resource. In this case you would have some rather static content for /library/books/{book-name} which can be cached on the client side. Then you would have /library/books/{book-name}/private-info which would be more volatile and user-dependent - and thus not easily cachable.
Building on this you can include a link to the private information in the original resource:
{
Title: "A book",
Author: "...",
PrivateInfoLink: "http://your-api.com/library/books/{book-name}/private-info"
}
The benefit of this is two-fold:
1) The server can leave out the link if the client does not have access to the private information and thus saving the client from a unnecessary round trip to (not) get the private info.
2) The server is free to change the private-info URL if it needs so later on (it could for instance be different URLs based on the user authorization).
If you want to read more about the benefits of hypermedia then try this: http://soabits.blogspot.dk/2013/12/selling-benefits-of-hypermedia.html
I recently answered a similar question. You can find my answer here.
The bottom line is: You should try to separate business logic from authorization logic always. This means you want to externalize your authorization. There are several ways of doing that.
In your particular case, imagine the list of sensitive fields that only a subset of clients can view changes over time, that would potentially require a rewrite of your API. If you decouple authorization logic from your business logic (API) then you can easily update authorization logic without having to rewrite any code. This is called externalized authorization management (see this great Gartner paper on the topic).
As part of my day-to-day job, I help clients secure APIs and web services using XACML. The best practice is always to keep concerns separate.

AppInventor: Fusion Tables SQL query UPDATE

I'm using fusion tables with an android app that I'm developing in AppInventor, and I had a question about the SQL Query for updating a row.
Now, before I ask the question, I will let you know that I would have included some screenshots of my blocks-editor code, but my boss told me I had to keep the app 100% closed source, so I can't provide any. Hopefully I'm not being too vague.
Anyways, I set a FusionTablesControl query using the "make text" block and the Google API UPDATE query, but when I send the query on my test device (Samsung Galaxy Player 5), the overlaying "Fusion Tables" load screen pops up for only a split second (it normally shows for 2 or 3 seconds). When I check the tables, there has been no change.
I think syntax is still a potential problem because when I typed the encoded URL into google chrome's address bar, it still didn't update the table. Here is the basic syntax of what I typed into the address bar.
https://www.googleapis.com/fusiontables/v1/query?sql=UPDATE%20tableID%20SET%20(Column1%3Ddata1%2C%20Column2%3Ddata2%2C%20Column3%3Ddata3%2C%20Column4%3Ddata4)%20WHERE%20ROWID%20%3D%20%27rowID%27
The decoded URL after the "sql=" part is:
UPDATE tableID SET (Column1=data1, Column2=data2, Column3=data3, Column4=data4) WHERE ROWID = 'rowID'
Any help would be appreciated.
Also, is it possible to set Google's API response to CSV instead of JSON?
Thanks,
~T16626
This does not work like that, because you did not use authentication. More about that see here:
Identifying your application and authorizing requests
Every request your application sends to the Fusion Tables API needs to
identify your application to Google. There are two ways to identify
your application: using an OAuth 2.0 token (which also authorizes the
request) and/or using the application's API key. Here's how to
determine which of those options to use:
If the request requires authorization (such as a request for an
individual's private data), then the application must provide an OAuth
2.0 token with the request. The application may also provide the API key, but it doesn't have to. If the request doesn't require
authorization (such as a request for public data), then the
application must provide either the API key or an OAuth 2.0 token, or
both—whatever option is most convenient for you.
To access a fusion table with App Inventor, you have 2 possibilities:
use the built-in fusiontable control blocks, how to set up everything for App Inventor please see the Pizza Party tutorial
use the web component with authentication, for details see here

Statelessness of a REST api with authenticated users

I'm currently designing a REST Http api. (With HATEOAS stuff, to make clients "simpler", and avoid clients to do complicated things, instead of letting the api tell them what to do ...)
Because of the social characteristic of the app, in order to interact with the application, users need to be authenticated, and each user will have a slighty different "view" of the data.
We'll take twitter as an example, it will be easier for everyone.
To authenticate users, we'll use OAuth, easy.
So, in the client (ios app...), a random user would maybe seeing a list of users should see:
Adrien: Following
John: Not Following
Rambo: Not Following
And another user would maybe see:
Adrien: Following
John: Not Following
Rambo: Following
To achieve this, the first solution would be for the client (in oauth term, the iphone/web/etc app), to get a list of all the users the authenticated user follow, and each time the client displays a list, compare each user with the list of followed users to know if it should display "Not Following" or "Following".
The requests/responses would be:
GET /users
Authorization: OAuth token...
[
{"id": 1, "name": "Adrien"},
{"id": 2, "name": "John"},
{"id": 3, "name": "Rambo"}
]
and
GET /users/{myid}/following
Authorization: OAuth token...
[1, 3, 25, 1210, 9]
This seems to be quite, stateless. Good.
Now what if i want to make client developers life easier, and embed directly in the user list response, the relationship of each user, relative to the authenticated user:
GET /users
Authorization: OAuth token...
[
{"id": 1, "name": "Adrien", "relationship": "Following"},
{"id": 2, "name": "John", "relationship": "Not Following"},
{"id": 3, "name": "Rambo", "relationship": "Following"}
]
So, questions:
It seems to break the "stateless" thing, does it really break the REST stateless constraint ?
Next, do you think it is a good or bad practice for an api to do this ?
You should definitely embed the relationship in the user list response. It would be bad practice to force the clients calculate it.
This does not break the stateless constraint of REST as it's the interactions that are stateless, not the systems. The server will almost always have to store and maintain state. For instance the server will need to maintain state of who is following who.
Finally, I think you are not fully getting the "State" part of Hypermedia As The Engine Of Application State. Basically, the resources are state machines. When you GET a resource, the valid state transitions are presented has hypermedia controls (links and forms) in the response. It's by following these links and submitting the forms that the client can change the state of these resources.
Including the description of the relationship type in the response body is not breaking the stateless constraint. The stateless constraint means that the web server can respond to the request without being dependent on any previous request (as has been mentioned by Tom, Jacob and kgb).
I'm not qualified to say whether what you're doing is a "best practice" or not, but in general Roy gave the following reasons for and against making your API stateless (see section 5.1.3 of his dissertation). Like many things in life there is a trade-off:
Problems with a Stateless System
Requests may need to be larger. Since data is not stored on the server between requests, each request may need include the same things over and over again.
In a stateless system, the server is dependent on the client maintaining the state correctly.
Benefits of a Stateless System
You know what a request is trying to achieve based solely on its content.
Reliability, since it "eases the task of recovering from partial failures". See reference 133 cited in Roys dissertation for more info.
Improved scalability. Managing state between requests, particularly in a distributed environment can be quite complex. The first thing that comes to mind here is ASP.NET InProc session state, fine for a single server, single process instance, but it doesn't scale very well.
RESTful Resources
Also, according to Roy's definition of a resource I'd take issue with how I think you're defining your resources, with each user getting a slighty different "view" of the data. Roy defines a resource as a membership function that varies over time (see section 5.2.1.1 in the dissertation). The user list resource you've defined above varies by both time and by the Authorization header. Two different clients requesting /users at the same time would most likely end up with completely different results. This will make caching the results more difficult.
EDIT: Using the HTTP vary header would allow it to be cached.
If you think adding "relationship" property to users breaking stateless constraint, then adding it when "/following" is in the request, would be breaking it too.
I would say "stateless" means no response depends from the other requests/responses.
HTTP is a stateless protocol, but it can store quite a lot of data about the user in the request/response headers(and i am not talking about sessions/cookies)
From Roy Fieldings Architectural Styles and
the Design of Network-based Software Architectures:
3.4.3 Client-Stateless-Server (CSS)
The client-stateless-server style derives from client-server with the additional
constraint that no session state is allowed on the server component.
Each request from client to server must contain all of the information necessary
to understand the request, and cannot take advantage of any stored context on
the server. Session state is kept entirely on the client.
Link: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
So you embedding entity data directly in the response does not make your solution non-stateless.
On good practice:
It's a lot better to actually serve the user data than a list of numbers for the client to figure out what to do with.
However, depending on the amount of data for each user, you could consider giving a list of links to the user resource and state the "follow" relation as well. Then the client can fetch the details on the needed users. Which solution you choose should depend on what you believe the client will be needing, you might end up using several approaches.
I don't see the correlation between embedding the "relationship" information into the /users resource and the stateless constraint. So I see no issue.
However, I would argue you are breaking the "identification of resources" constraint.
/Users for you and /Users for me is going to show a completely different set of relationships. I would argue those are two different resources and therefore should have distinct URIs.
There are some scenarios where you can change a representation based on who the user is (for security reasons for example) but this case is just too much change for my liking.