Get headers from http response - elm

I am new to elm,
I have a login api which returns a JWT token in its hedears
curl http://localhost:4000/api/login?email=bob#example&password=1234
response:
HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8
success
now Im trying to write a function that will send request and return the token from the headers in elm
authUser =
Http.send "http://localhost:4000/api/login?email=bob#example&password=1234"
how do I do this in a simple way?

In order to extract a header from a response, you will have to use Http.request along with the expectStringResponse function, which includes the full response including headers.
The expectStringResponse function takes a Http.Response a value, so we can create a function that accepts a header name and a response, then returns Ok headerValue or Err msg depending on whether the header was found:
extractHeader : String -> Http.Response String -> Result String String
extractHeader name resp =
Dict.get name resp.headers
|> Result.fromMaybe ("header " ++ name ++ " not found")
This could be used by a request builder like so:
getHeader : String -> String -> Http.Request String
getHeader name url =
Http.request
{ method = "GET"
, headers = []
, url = url
, body = Http.emptyBody
, expect = Http.expectStringResponse (extractHeader name)
, timeout = Nothing
, withCredentials = False
}
Here is an example on ellie-app.com which returns the value of content-type as an example. You can substitute "authorization" for your purposes.

May I humbly suggest you look at my elm-jwt library, and the get function there?
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResult
JWT tokens normally need to be sent as a Authorization header and this function helps you create a Request type that can be passed to Http.send or Jwt.send

Related

Karate - Trouble passing correct headers for authorization

I am have some problems passing in the correct headers for my graphql endpoints
The use case in Postman:
call requestToken endpoint to obtain sessionToken value
requestToken response contains Key Value " and Token Value.
For subsequent calls, I set postman headers as:
Key = X_SESSION_TOKEN Value = Token Value
The user case in Karate
1st feature 'requestToken.feature' successfully calls and stores key + tokenValue
2nd feature successfully defines and prints the token value
here is my 2nd request:
Feature: version
Background:
* url 'http://api-dev.markq.com:5000/'
* def myFeature = call read('requestToken.feature')
* def authToken = myFeature.sessionToken
* configure headers = { 'X_SESSION_TOKEN': authToken , 'Content-Type': 'application/json' }
Scenario: get version
Given path 'query'
Given text query =
"""
query {
version
}
"""
And request { query: '#(query)' }
When method POST
Then status 200
And print authToken
And print response
I am not sure I send the headers right. Its coming back 200, but I keep getting a error 'token malformed' in the response message
Any suggestions? New at this, thanks!
Honestly this is hard to answer, a LOT depends on the specific server.
EDIT: most likely it is this change needed, explained here: https://github.com/intuit/karate#embedded-expressions
* configure headers = { 'X_SESSION_TOKEN': '#(authToken)' , 'Content-Type': 'application/json' }
2 things from experience:
should it be X-SESSION-TOKEN
add an Accept: 'application/json' header
And try to hardcode the headers before attempting call etc.
Here is an example that works for me:
* url 'https://graphqlzero.almansi.me/api'
* text query =
"""
{
user(id: 1) {
posts {
data {
id
title
}
}
}
}
"""
* request { query: '#(query)' }
* method post
* status 200

Getting header with selenium-wire python

Need to get header from request with selenium wire. I'm taking cookie from header
result_cookies = ""
for request in self.browser.iter_requests():
result = request.headers.get("cookie")
if result:
if len(result_cookies) < len(result):
result_cookies = result
But I have there different cookies, where userCategory=PU, and userCategory=LIM, how i can get cookie where userCategory is LIM.
Part of cookie:
g2usersessionid=e792fb427388bfbfd2f6d8c82163d763; G2JSESSIONID=A27799E20A8A42058502875CD1617C61-n1; userLang=en; visid_incap_242093=ivG0wNBcTX2qbGGfef/Kzsp15WAAAAAAQUIPAAAAAAALk1ZNmpA0m0hbUNh68t/9; incap_ses_260_242093=g/XKTK5T3TznIlAEpLSbA8p15WAAAAAALxw6bB7fGHsf1fHHG2AGPg==; userCategory=LIM; copartTimezonePref=%7B%22displayStr%22%3A%22CEST%22%2C%22offset%22%3A2%2C%22dst%22%3Atrue%2C%22windowsTz%22%3A%22Europe%2FBerlin%22%7D; timezone=Europe%2FBerlin;
This how I make use of selenium-wire to get the cookie from the headers:
for request in self.driver.requests:
if request.response:
print(
request.url,
request.response.status_code,
request.response.headers['Content-Type'],
request.response.headers['set-cookie']
)
if "ivc_id" in request.response.headers['set-cookie']:
cookie=request.response.headers['set-cookie']
print(cookie)
Is this what you are looking for?

What argument is Http.Request missing?

I'm trying to create an Http.Request value:
request : Http.Request
request =
{ verb = "POST"
, headers =
[ ( "Origin", "http://elm-lang.org" )
, ( "Access-Control-Request-Method", "POST" )
, ( "Access-Control-Request-Headers", "X-Custom-Header" )
]
, url = url
, body = body
}
The code is embedded in the function below:
tryRegister : Form -> (Result Http.Error JsonProfile -> msg) -> Cmd msg
tryRegister form msg =
let
url =
baseUrl ++ "register"
body =
encodeRegistration form |> Http.jsonBody
request : Http.Request
request =
{ verb = "POST"
, headers =
[ ( "Origin", "http://elm-lang.org" )
, ( "Access-Control-Request-Method", "POST" )
, ( "Access-Control-Request-Headers", "X-Custom-Header" )
]
, url = url
, body = body
}
in
Http.send msg request
I receive the following error:
Type Http.Request has too few arguments. - Expecting 1, but got 0.
What argument is Http.Request missing?
Appendix:
http://package.elm-lang.org/packages/evancz/elm-http/3.0.1/Http
Your appendix link is to an old version of the Http package. The new package is elm-lang/http. The type parameter that Request expects is the type to use in a successful response, which in your case looks like it should be JsonProfile.
The evancz/elm-http package is deprecated, you are probably actually using elm-lang/http so you're looking at the wrong documentation.
To construct a Http.Request using elm-lang/http you need to call the Http.request function and pass it a record describing the request.
http://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#request
Additionally you can't actually set the 'Origin' header for a request from within the browser this means you'll won't need to set any headers at all and can just use the Http.post helper function http://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#post

Elm get raw JSON string

I'm trying to build a very simple app that will just output the raw JSON object from an api.
So I want a function that will take a url parameter and ideally return the JSON string.
I have the following code:
decode: String -> String
decode jsonString =
Decode.decodeString jsonString
apiResonse : String -> String
apiResonse url =
let
url = "https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats"
request = Http.get Decode.decodeString url
in
Http.send NewRequest request
But I'm struggling to understand the decoder part of the function. If anyone could help me that would be great.
If you just want to get the HTTP response as a string value, use Http.getString. The example you posted using Http.get assumes the result is in JSON and forces you to decode it to an Elm value.
Here is a modified example of the random cat generator code which just displays a dump of the response JSON instead of a cat picture:
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
in
Http.send NewGif (Http.getString url)
Here is a working example on ellie-app.com

Elm read HTTP response body for non-200 response

How to read HTTP response body for a non 200 HTTP status
getJson : String -> String -> Effects Action
getJson url credentials =
Http.send Http.defaultSettings
{ verb = "GET"
, headers = [("Authorization", "Basic " ++ credentials)]
, url = url
, body = Http.empty
}
|> Http.fromJson decodeAccessToken
|> Task.toResult
|> Task.map UpdateAccessTokenFromServer
|> Effects.task
The above promotes the error from
Task.toResult : Task Http.Error a -> Task x (Result Http.Error a)
The value of which becomes
(BadResponse 400 ("Bad Request"))
My server responds with what is wrong with the request as a JSON payload in the response body. Please help me retrieve that from the Task x a into ServerResult below.
type alias ServerResult = { status : Int, message : String }
The Http package (v3.0.0) does not expose an easy way to treat HTTP codes outside of the 200 to 300 range as non-error responses. Looking at the source code, the handleResponse function is looking between the hardcoded 200 to 300 range
However, with a bit of copy and pasting from that Http package source code, you can create a custom function to replace Http.fromJson in order to handle HTTP status codes outside the normal "success" range.
Here's an example of the bare minimum you'll need to copy and paste to create a custom myFromJson function that acts the same as the Http package except for the fact it also treats a 400 as a success:
myFromJson : Json.Decoder a -> Task Http.RawError Http.Response -> Task Http.Error a
myFromJson decoder response =
let decode str =
case Json.decodeString decoder str of
Ok v -> Task.succeed v
Err msg -> Task.fail (Http.UnexpectedPayload msg)
in
Task.mapError promoteError response
`Task.andThen` myHandleResponse decode
myHandleResponse : (String -> Task Http.Error a) -> Http.Response -> Task Http.Error a
myHandleResponse handle response =
if (200 <= response.status && response.status < 300) || response.status == 400 then
case response.value of
Http.Text str ->
handle str
_ ->
Task.fail (Http.UnexpectedPayload "Response body is a blob, expecting a string.")
else
Task.fail (Http.BadResponse response.status response.statusText)
-- copied verbatim from Http package because it was not exposed
promoteError : Http.RawError -> Http.Error
promoteError rawError =
case rawError of
Http.RawTimeout -> Http.Timeout
Http.RawNetworkError -> Http.NetworkError
Again, that code snippet is almost entirely copy and pasted except for that 400 status check. Copying and pasting like that is usually a last resort, but because of the library restrictions, it seems to be one of your only options at this point.